Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.
Menu
PHP TUTORIALS


PHP Strings

In the previous PHP Variables chapter, we showed you how to create a simple string variable.
We'll now show you a few things you can do with it.

To re-cap, here's a simply string variable: In PHP, variables start with a "$" sign, so "$hello" is a variable called "hello". To store data in that variable, we would simply say:
<?PHP
$hello = "Hi, my name is Simon.";
?>


There are lots of standard (built-in) functions in PHP dedicated to working with strings, so I won't list all of them, but here's a few I use all the time:

What if we wanted to join 2 string variables together? We need to concatenate them... concatenate means "to link together".
In PHP the concatenation operator (symbol) is the full stop (.): <?PHP
$text1 = "Hi, my name is Simon.";
$text2 = "I'm very please to meet you!";
$combined = $text1." ".$text2;
echo $combined;
?>
This would print "Hi, my name is Simon. I'm very pleased to meet you!".
We've taken the variable $text1 and concatenated it (joined it) to whatever is between the quote marks (in this case a space), and then concatenated (joined) variable $text2 onto the end.

What if we wanted to know how long a string is: <?PHP
$text = "Hi, my name is Simon.";
echo strlen($text);
?>
This would print "21".

What if we wanted to take a string and make it into an array: <?PHP
$vegstring = "peas & carrots & parsnips & potatoes & broccoli";
$veg=explode(" & ",$vegstring);
?>
We would now have an array called $veg that looked like $veg=array("peas","carrots","parsnips","potatoes","broccoli");.

What if we wanted to take an array and make it into a string: <?PHP
$veg=array("peas","carrots","parsnips","potatoes","broccoli");
$vegstring=implode(" & ",$veg);
echo $vegstring;
?>
This would print "peas & carrots & parsnips & potatoes & broccoli".

The last two examples demonstrate how to get an array from a string, or a string from an array. See the section on PHP Arrays for more information.


Title