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));
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
array ( 0 => 500, 1 => 500, 2 => 450, 3 => 500, 4 => 400, 5 => 300, 6 => 300, 7 => 300, 8 => 300, )

preferences:
71 ms | 1117 KiB | 4 Q