PHP's implode function returns a string consisting of array element values joined using a string that you specify:
Code: Select all
$ar = ['apple', 'orange', 'pear', 'grape'];
echo implode(', ', $ar);
// apple, orange, pear, grape
Code: Select all
$ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
echo implode($ar); // abcdefg
Code: Select all
$ar = [true, false, 0, 1, NULL, 1.42];
echo implode(', ', $ar); // 1, , 0, 1, , 1.42
Convert Array of Arrays to String
If the array you pass to the implode function contains elements that are arrays, Array will be the output for each sub-array:
Code: Select all
$food = [
'fruits' => ['apple', 'raspberry', 'pear', 'banana'],
'vegetables' => ['peas', 'carrots', 'cabbage'],
'grains' => ['wheat', 'rice', 'oats']
];
echo implode(', ', $food);
// Array, Array, Array
An array consisting of a single level of sub-arrays, like the example above, could be converted to a string using the following function:
Code: Select all
function subArraysToString($ar, $sep = ', ') {
$str = '';
foreach ($ar as $val) {
$str .= implode($sep, $val);
$str .= $sep; // add separator between sub-arrays
}
$str = rtrim($str, $sep); // remove last separator
return $str;
}
// $food array from example above
echo subArraysToString($food);
// apple, raspberry, pear, banana, peas, carrots, cabbage, wheat, rice, oats
Other Ways to Convert to String
PHP offers more ways to convert arrays and other values to strings: json_encode and serialize. First we demonstrate applying json_encode to the following array:
Code: Select all
$person = [
'name' => 'Jon',
'age' => 26,
'status' => null,
'friends' => ['Matt', 'Kaci', 'Jess']
];
echo json_encode($person);
// {"name":"Jon","age":26,"status":null,"friends":["Matt","Kaci","Jess"]}
Next we pass the same array to the serialize function:
Code: Select all
echo serialize($person);
// a:4:{s:4:"name";s:3:"Jon";s:3:"age";i:26;s:6:"status";N;s:7:"friends";a:3:{i:0;s:4:"Matt";i:1;s:4:"Kaci";i:2;s:4:"Jess";}}
implode and explode
PHP's explode function does the opposite of implode: it converts a string to an array.
https://www.dyn-web.com/php/arrays/convert.php