implode() function is used to join arrays. It joins an array with a given glue and returns a string.
The implode function has two arguments. implode(glue, array)
<?php $array = ['Breakfast', 'Lunch', 'Dinner']; echo implode(', ', $array); // Breakfast, Lunch, Dinner
When using implode() with associative arrays, the keys will be ignored. Values will be joined.
<?php $array = [ 'best' => 'Apple', 'worst' => 'Pineapple', 'good' => 'Banana' ]; echo implode('|', $array); // Apple|Pineapple|Banana
Note: implode() cannot be used with multi-dimensional arrays
Let's play with the glue argument in the implode() function.
<?php $array = ['Apple', 'Banana', 'Pineapple']; echo implode('', $array); // AppleBananaPineapple echo implode(' and ', $array); // Apple and Banana and Pineapple echo implode('<br>', $array); # using HTML // WTH? Reverse works? Yes!! PHP knows your mistakes echo implode($array, ',');
explode() function is used to split strings. It splits a string by a delimeter, and returns an array.
The explode function has two arguments. explode(delimeter, string)
If the string is Apple,Banana, and the delimeter is ,, you will get an array with two elements Apple and Banana. The important thing to notice is that delimeter is not included in the splitted elements. They work excatly as boundaries.
<?php $str = 'Apple, Banana, Cherry'; print_r( explode(',', $str) ); // There's an anoying whitespace // No more whitespaces in element // now the boundary (delimeter) is ', ' // string chunks around the delimeter will be elements of array print_r( explode(', ', $str) );
<?php $str = 'Hyvor Developer:developer.hyvor.com'; list($title, $url) = explode(':', $str); echo $title; echo $url;
Unlike implode(), explode()'s arguments cannot be reversed. The reason is: in implode(), each argument was in different data types (string and array). But, both arguments of explode() are strings. Therefore PHP doesn't have a way to identify them seperately. So, for both functions, remember to use the delimeter or glue first to reduce mistakes.