3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ 0 => 50, 1 => 200, 2 => 75, 3 => 150, 4 => 100, 5 => 125, 6 => 150, 7 => 300, 8 => 300, 9 => 300, 10 => 300, 11 => 300, 12 => 300, 13 => 300, 14 => 300, 15 => 300, ]; function consolidate(array $array, int $capacity = 500): array { rsort($array); $bins = [0]; foreach ($array as $value) { foreach ($bins as &$bin) { if ($capacity >= $bin + $value) { $bin += $value; continue 2; } } $bins[] = $value; } return array_values(array_filter($bins)); } var_export(consolidate($array));

preferences:
30.17 ms | 407 KiB | 5 Q