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.