How to use implode in PHP 8

Description

Joining an array of strings is a fairly common operation that PHP developers have to do. For this purpose, you would use the implode() function. For instance, you may have a tree representation of your website paths and want to generate the final slug of a website page. Another example would be custom logic to create a hash value consisting of different strings so that the entropy of the generated hash is higher.

implode in PHP 8

implode(string $separator, array $array): string

The implode function takes 2 parameters. The first one is the $seperator which defines how the array should be converted to a string. The second parameter is the $array which should be joined together by the previously set $seperator. The result of the operation is the joined array as string.

Example

$array = array('Php', 'is', 'cool.');

$separator = ' ';

$result = implode($separator, $array);

echo $result;

The example from above will generate the following output:

Php is cool.

Additionally, you can use the implode with associative arrays as the keys of the array are ignored while joining the values. Below you will find the adapted version from above. Notice that the keys of the associative array play no role in the result of the implode function.

$array = array('test=3' => 'Php', 'test2' => 'is', 'test1' => 'cool.');

$separator = ' ';

$result = implode($separator, $array);

echo $result;

The example from above will generate the following output:

Php is cool.

In order to reverse the operation, you would use the sibling function explode in PHP 8.

Edgecases

A common edgecase is passing an empty array to the implode function. In this case, implode will simply return a string with no characters.

$array = array();

$separator = ' ';

$result = implode($separator, $array);

echo '/'. $result . '/';

The example from above will generate the following output:

//

Passing null to implode as the $array will throw an error. Passing null as the $seperator parameter will be interpreted as an empty string ''.

Finally, if you pass an array of arrays like array(array('Php'), array('is'), array('cool.')) to the implode function, it will throw an error. You first have to map the inner arrays to a string before you can use implode. In this case, you could just use implode('', $element) on each element to achieve this goal.