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 { arsort($array); $bins = [[]]; foreach ($array as $value) { $added = false; foreach ($bins as &$bin) { if ($capacity >= (array_sum($bin) + $value)) { $bin[] = $value; $added = true; continue 2; } } if (!$added) { $bins[] = [$value]; } } return array_map('array_sum', array_filter($bins)); } var_export(consolidate($array));
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
array ( 0 => 500, 1 => 500, 2 => 450, 3 => 500, 4 => 400, 5 => 300, 6 => 300, 7 => 300, 8 => 300, )

preferences:
112.43 ms | 402 KiB | 89 Q