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:
$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 (.):
This would print "Hi, my name is Simon. I'm very pleased to meet you!".
$text1 = "Hi, my name is Simon.";
$text2 = "I'm very please to meet you!";
$combined = $text1." ".$text2;
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.
<?PHPThis would print "21". What if we wanted to take a string and make it into an array:
$text = "Hi, my name is Simon.";
<?PHPWe would now have an array called $veg that looked like $veg=array("peas","carrots","parsnips","potatoes","broccoli");.
$vegstring = "peas & carrots & parsnips & potatoes & broccoli";
$veg=explode(" & ",$vegstring);
What if we wanted to take an array and make it into a string:
<?PHPThis would print "peas & carrots & parsnips & potatoes & broccoli".
$vegstring=implode(" & ",$veg);
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.