The PHP builtin function implode(), is used to join the elements of an array with a separator string.
The syntax of implode:
implode(string $separator, array $array): string
Parameters
separator: It is an optional parameter and its default value is an empty string.
array: It is an array of strings to implode
Examples of implode are:
- An Array to string
$colors = [ 'red', 'white', 'blue', 'black' ]; $colors = implode( ", ",$colors ); echo 'Colors are: '.$colors;
Output
2. An Associative array to string
It is complex to join the key and value of an associative array using only implode function. Combining array_walk() and implode() functions of the PHP will make the job easier.
The array_walk() function walks through each element of an array in a user-defined callback function regardless of pointer position.
array_walk(array|object &$array, callable $callback, mixed $arg = null): bool
Parameters
array: The input array.
callback: Typically, a callback takes on two parameters. The array parameter’s value is the first, and the key/index second.
arg: arg is an optional parameter. If the callback function requires more than 2 parameters, the arg parameter is supplied. It is passed as the third parameter to the callback.
$style = [ 'color' => 'red', 'background-color' => 'blue' ]; array_walk($style, function(&$value, $key) { $value = "{$key}:{$value}"; }); $divStyle = 'style="'.implode(';', $style).'"'; echo 'You can use this style in div: ‘. $divStyle;
Output
3. Multidimensional array to string
$style = [ 'Color' => ['red','blue','green','red'], 'Shape' => ['rectangle','square','triangle','diamond'] ]; array_walk($style, function(&$value, $key) { $value = implode(', ',$value); $value = "{$key}: {$value}"; }); echo implode('<br/>',$style);
Output
Views: 6