Splitting and joining PHP variables and strings

Sometimes you want to split a variable into parts. Remember how FOREACH goes through an array line by line. Imagine that this information had been read from a text file:

Imagine that this data is in an array:

$stocklist[0]="oranges, 50p, Spain";
$stocklist[1]="bananas, 40p, Windward Island";
$stocklist[2]="apples, 30p, UK";
        

This loop might output the contents to a page:

            
foreach ($stocklist as $item) {
    echo "<p>$item</p>";            
}                        
        

To use that data properly though you would need to split it up into parts. Each line is made up of:

You can split those three things up because they are separated by commas. There are a number of built in PHP functions which do this job but explode() is probably best. It will take a string and split it every time there is a special character (e.g. a comma). This code goes through the array bit by bit and explodes each bit:

foreach ($stocklist as $item) {
    $itemarray=explode(",", $item);
    echo "<pre>";
    print_r($itemarray);
    echo "</pre>";
}
        

The string is split into an array. Paste that into arraysandloops.php and you should see three arrays printed each with a stock item name, price and country in it. One array is printed each time through the loop.

Extra spaces and TRIM

When splitting text you may find you end up with extra blank spaces at the beginning and end of the data. The problem is that if you then use the data in conditional statements (e.g. IFs) you may not get matches because of the extra spaces. TRIM removes any extra blank spaces (including invisible carriage returns and tabs):

$string="      a string with spaces at beginning and end     "; 
$string=trim($string);
echo "String is |$string|";
        

The | characters are there to let you see any remaining spaces and don't do anything. Any symbol could have been used.

Try creating some variables holding strings and then splitting them by different special characters

Joining strings

You can also join strings together. To join the strings held in two variables:

$both=$first.$second;                
        

To join a variable and a literal:

$both=$first."a piece of text in quotes is known as a string literal for reasons which do not matter.";
        

Or alternatively you can just include the variables inside the double-quoted string:

$both="A string of text can have $first variables in it like this.";                
        

Remember that if the strings being manipulated have quotes or other reserved characters in you need to tell PHP that they are part of the string and not part of the code. For example this would look to PHP like a string with two variables (one which is invalid as it begins with a number not a letter) followed by a coding error when the quotes in the string ended the string prematurely:

        
$both="This $stockitemname is worth $40 to which you might say "Wow, cheap".";
        

The string should look like this:

        
$both="This $stockitemname is worth \$40 to which you might say \"Wow, cheap\".";
        

Now the slashes tell PHP which characters are part of the string.

Try joining different strings and variables in different ways and test the results

submit to reddit Delicious Tweet