explode() and implode() php arrays

by Carey on December 8, 2010

Post image for explode() and implode() php arrays
  • Share
  • CevherShare
  • Share

No this isn’t about getting frustrated with PHP and nuking your server, this is a couple of very useful (although hard to remember) array functions.

explode() will take a string and give you an array, splitting that string on the delimiter you give. For example, if you have a list of comma seperated values you will work this as follows:

$monkeys = 'bubbles,charlie,george';
$monkeysArray = explode($monkeys,',');
var_dump($monkeysArray); # shows you the array

There is also an optional third parameter, $limit, which will restrict the number of array elements created.

implode() will do the opposite; pass it an array and the glue and in return you will get a string of each array element joined by the glue:

$monkeysArray = array('bubbles','charlie','george');
$monkeys = implode(' and ',$monkeysArray);
echo $monkeys; # gives you "bubbles and charlie and george"

I could never remember which function is which, so I now imagine “exploding” a string to create an array.

Leave a Comment

Previous post:

Next post: