<?php $weight_distribution = [ '1' => 0, '2-5' => 0, '5-10' => 6, '10-15' => 7, '15-20' => 3, ]; function distribute_weights(int|float $weight, array &$distribution): void { $parsed = []; foreach ($distribution as $range => $cost) { if (sscanf($range, '%d-%d', $min, $max) === 1) { $default = [$min, $min]; } else { $parsed[] = [$min, $max]; } } while ($weight > 0) { foreach ($parsed as $i => [$min, $max]) { if ($weight <= $max) { if (!$i && $weight <= $min) { [$min, $max] = $default; } break; } } if ($min === $max) { ++$distribution[$max]; } else { ++$distribution[$min . '-' . $max]; } $weight -= $max; } } distribute_weights(21, $weight_distribution); print_r($weight_distribution);
You have javascript disabled. You will not be able to edit any code.