3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ '5' => 142, '2' => 57, '0' => 0, '18' => 37, '3' => 13, '6' => 101, ]; $groupLimit = 50; $result = []; $groupKey = 0; foreach ($array as $key => $value) { while ($value) { $sum = array_sum($result[$groupKey] ?? []); // get group sum $value -= $result[$groupKey][$key] = min($groupLimit - $sum, $value); // push key with limited value; decrease value $groupKey += ($sum + $result[$groupKey][$key] === $groupLimit); // only increment group key if at $groupLimit } } var_export($result);

preferences:
42.52 ms | 402 KiB | 5 Q