3v4l.org

run code in 300+ PHP versions simultaneously
<?php $rules = [ '1' => '1.2', '5-10' => '6.25', '10-15' => '9.2', '15-20' => '10.9', ]; function costFromWeight($weight, array $newRules): array { $parsed = []; foreach ($newRules as $range => $cost) { if (sscanf($range, '%d-%d', $min, $max) === 1) { $default = [$min, $min, (float) $cost]; } else { $parsed[] = [$min, $max, (float) $cost]; } } $result = ['cost' => 0]; while ($weight > 0) { foreach ($parsed as $i => [$min, $max, $cost]) { if ($weight <= $max) { if (!$i && $weight <= $min) { [$min, $max, $cost] = $default; } break; } } $result[$max] = ($result[$max] ?? 0) + 1; $result['cost'] += $cost; $weight -= $max; } return $result; } foreach ([49, 47.75, 38, 35, 23, 15, 14, 10.5, 4] as $weight) { echo "$weight :: "; print_r(costFromWeight($weight, $rules)); echo "\n---\n"; }
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
49 :: Array ( [cost] => 28.05 [20] => 2 [10] => 1 ) --- 47.75 :: Array ( [cost] => 28.05 [20] => 2 [10] => 1 ) --- 38 :: Array ( [cost] => 21.8 [20] => 2 ) --- 35 :: Array ( [cost] => 20.1 [20] => 1 [15] => 1 ) --- 23 :: Array ( [cost] => 14.5 [20] => 1 [1] => 3 ) --- 15 :: Array ( [cost] => 9.2 [15] => 1 ) --- 14 :: Array ( [cost] => 9.2 [15] => 1 ) --- 10.5 :: Array ( [cost] => 9.2 [15] => 1 ) --- 4 :: Array ( [cost] => 4.8 [1] => 4 ) ---

preferences:
80.71 ms | 403 KiB | 62 Q