explode() and implode() php arrays
Last Updated on: November 27, 2022
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-separated values, you will work this as follows:
$monkeys = 'bubbles,charlie,george'; $monkeysArray = explode($monkeys,','); var_dump($monkeysArray);
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 you will get a string of each array element joined by the glue:
$monkeysArray = array('bubbles','charlie','george'); $monkeys = implode(' and ',$monkeysArray); echo $monkeys; // Outputs "bubbles and charlie and george"
If you struggle to remember which function is which, try imaging “exploding” a string to create an array.
Get notified of new posts: