'Split array into 4-element chunks then implode into strings

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

I want output like

['1, 2, 3, 4', '5, 6, 7, 8', '9'];


Solution 1:[1]

You can use array_chunk() to split your array into chunks of 4 items. Then array_map() to implode() each chunk:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunk = array_chunk($array, 4);
var_dump(array_map(fn($item) => implode(', ', $item), $chunk));

Outputs:

array(3) {
  [0]=> string(7) "1, 2, 3, 4"
  [1]=> string(7) "5, 6, 7, 8"
  [2]=> string(1) "9"
}

Solution 2:[2]

you can do that

const $array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const $chunk = $array.reduce((r,v,i)=>
  {
  if (!(i%4))  r.pos         = r.resp.push(`${v}`) -1
  else         r.resp[r.pos] += `,${v}`
  return r
  }, { resp : [], pos:0 } ).resp


console.log( $chunk )

Solution 3:[3]

For best efficiency in terms of time complexity, loop over the array only once. As you iterate, divide the index by 4 and "floor" or "truncate" the dividend to form grouping keys.

When a grouping key is encountered more than once, prepend the delimiting comma-space before appending the new string value to the group's string.

Code: (Demo)

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

foreach ($array as $i => $v) {
    $group = (int) ($i / 4);
    if (isset($result[$group])) {
        $result[$group] .= ", $v";
    } else {
        $result[$group] = "$v";
    }
}
var_export($result);

More concisely, you can split the array into 4-element rows and then implode those elements to form your delimited strings. This has more expensive time complexity because it iterates more times than the number of elements in the input array. (Demo)

var_export(
    array_map(
        fn($v) => implode(', ', $v),
        array_chunk($array, 4)
    )
);

You could also consume the input array as you isolate 4 elements at a time with array_splice(), but this is probably the least advisable since it eventually erases all of the data in the input array. (Demo)

$result = [];
while ($array) {
    $result[] = implode(', ', array_splice($array, 0, 4));
}
var_export($result);

Output from all above techniques:

array (
  0 => '1, 2, 3, 4',
  1 => '5, 6, 7, 8',
  2 => '9',
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mister Jojo
Solution 3 mickmackusa