PHP Implode Explode

PHP implode() and explode() are the couple of popularly used string functions. Both are used to convert a string or array data from one another and these are a complement to each other.

PHP Implode

implode() function accepts a separator and an array as its parameter. It combines each of the array elements whereas the combined elements are separated with the separator. For example,

$str_concat = "|";
$meaning_array = array("implode","join","concatenate");
$imploded_string = implode($str_concat,$meaning_array);
echo $imploded_string; // implode|join|concatenate

This program will return combined array elements separated by the (|) symbol. There are no strict rules for the arguments order of this function. For example, we can use implode as like as,

...
$imploded_string = implode($meaning_array,$str_concat);
...

php_implode_explode

PHP Explode

On the other hand, explode() is to split the string into an array of elements with respect to the given separator. explode() accepts separator and a string as its argument.

PHP explode() Example

$input_string = "implode|join|concatenate";
$str_explode = "|";
$exploded_array = explode($str_explode,$input_string );
echo "<pre>";
print_r($exploded_array); 
echo "</pre>";

This program accepts the resultant string data of implode example we have seen above. As we given the same separator string (|), explode() splits string data and reproduce the original array we have given for imploding. The output of this program will explode

Array
(   [0] => implode
    [1] => join
    [2] => concatenate
)

( ) is used as an alternative for split(), a deprecated PHP function. We have seen the reason for why split() is deprecated.

PHP explode() accepts a third optional argument limit to set target length or boundary for performing explode operation. explode() will take entire string if nothing is specified a a limit.

Explode within Limit

$exploded_array = explode($str_explode,$input_string,2);

this will return,

Array
(   [0] => implode
    [1] => join|concatenate
)

Note:

  • The limit argument should be a positive integer.
  • As like implode(), we cannot change the order of arguments for the explode() function.

This PHP code tutorial was published on May 30, 2013.

↑ Back to Top