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.
$myarray = â€œalexâ€; $myarray = â€œ123 fake stâ€; $myarray = â€œsunnybankâ€; $mycombinedstring = implode(â€œ|â€, $myarray); echo $mycombinedstring; // Prints alex|123 fake st|sunnybank
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.
$mycombinedstring = â€œalex|123 fake st|sunnybankâ€; $myarray = explode(â€œ|â€, $mycombinedstring); echo $myarray; // Prints alex echo $myarray; // Prints 123 fake st echo $myarray; // Prints sunnybank
Using implode and explode is just that simple. In the next PHP code of the week weâ€™ll talk about using cookies.