PHP Snippet 1:
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunk = array_chunk($array, 4);
var_dump(array_map(fn($item) => implode(', ', $item), $chunk));
PHP Snippet 2:
array(3) {
[0]=> string(7) "1, 2, 3, 4"
[1]=> string(7) "5, 6, 7, 8"
[2]=> string(1) "9"
}
PHP Snippet 3:
$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);
PHP Snippet 4:
var_export(
array_map(
fn($v) => implode(', ', $v),
array_chunk($array, 4)
)
);
PHP Snippet 5:
$result = [];
while ($array) {
$result[] = implode(', ', array_splice($array, 0, 4));
}
var_export($result);
PHP Snippet 6:
array (
0 => '1, 2, 3, 4',
1 => '5, 6, 7, 8',
2 => '9',
)