I have an array
Array ( [0] => '2' [1] => '3' [2] => '4' [3] => '5' [4] => '6' [5] => '7' )
I want to join them per 3 items like below
Array ( [0] => '2,3,4' [1] => '5,6,7' )
Does anyone have an idea?
Use array_chunk() to split the array into blocks of 3 entries, then array_walk() or array_map() with a callback that uses implode() to join that block of three elements into one string with comma separators.
$result = array_map(
function ($value) {
return implode(',', $value);
},
array_chunk($myArray, 3)
);
You can use just array_chunk():
// Array definition
$array = array(0 => '2', 1 => '3', 2 => '4', 3 => '5', 4 => '6', 5 => '7');
// New array: [ 0 => [2, 3, 4], 1 => [5, 6, 7] ]
$resultArray = array_chunk($array, 3);
// Join the elements with comma
foreach($resultArray as &$row){
$row = implode(',', $row);
}