PHP COTW: implode and explode

This weeks PHP code of the week is implode and explode which allow you to combine arrays and split up chunks of text by certain characters.

implode as mentioned above allows you to combine an array with more than one element into a string with elements separated by certain characters.

Say we have a username, address and suburb in an array and want to combine it into one string to save space, we could use implode like so.

[php]$myarray[0] = “alex”;
$myarray[1] = “123 fake st”;
$myarray[2] = “sunnybank”;

$mycombinedstring = implode(“|”, $myarray);

echo $mycombinedstring; // Prints alex|123 fake st|sunnybank[/php]

It’s recommended that the certain character or characters be some character that you don’t accept in user input or some special code if needed.

explode is basically the opposite of implode, it breaks up a string based on certain characters and places each chunk into an element of the choose array.

[php]$mycombinedstring = “alex|123 fake st|sunnybank”;

$myarray = explode(“|”, $mycombinedstring);

echo $myarray[0]; // Prints alex
echo $myarray[1]; // Prints 123 fake st
echo $myarray[2]; // Prints sunnybank[/php]

Using implode and explode is just that simple. In the next PHP code of the week we’ll talk about using cookies.

Leave a Reply