3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [11, 3, 45, 6, 61, 89, 22]; function array_slimmer(array $array, int $finalCount): array { // no work to be done if we're asking for more than what the array holds // same goes if we're asking for just one array or (nonsensical) less if ($finalCount >= count($array) || $finalCount < 2) { return $array; } return array_map(function (array $chunk) { // rounded to two decimals, but you can modify to accomodate your needs return round(array_sum($chunk) / count($chunk), 2); }, custom_chunk($array, $finalCount)); } function custom_chunk($array, $maxrows) { $size = sizeof($array); $columns = ceil($size / $maxrows); $fullrows = $size - ($columns - 1) * $maxrows; for ($i = 0; $i < $maxrows; ++$i) { $result[] = array_splice($array, 0, ($i < $fullrows ? $columns : $columns - 1)); } return $result; } print_r(array_slimmer($array, 2)); print_r(array_slimmer($array, 3)); print_r(array_slimmer($array, 4));

preferences:
26.57 ms | 409 KiB | 5 Q