3v4l.org

run code in 300+ PHP versions simultaneously
<?php $order = 99; $sizes=[21,18,12,6]; $b = [21 => 0, 18 => 0, 12 => 0, 6 => 0]; // number of 21 boxes possible if($order >= 21){ $b[21] = floor($order/21); $order -= $b[21]*21; } // if the remainder needs to be modified to be divisible on 6 while($order % 6 != 0){ if($b[21] > 0){ // remove one box of 21 and add the bottles back to the remainder $order += 21; $b[21]--; }else{ // if we run out of 21 boxes then the order is not possible. echo "order not possible"; exit; } } // split up the remainder on 18/12/6 boxes and remove empty boxes $b = array_filter(split_up($b, $order)); var_dump($b); function split_up($b, $order){ // number of 18 boxes possible if($order >= 18){ $b[18] = floor($order/18); $order -= $b[18]*18; } // number of 12 boxes possible if($order >= 12){ $b[12] = floor($order/12); $order -= $b[12]*12; } // number of 6 boxes possible if($order >= 6){ $b[6] = floor($order/6); $order -= $b[6]*6; } return $b; }
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
array(2) { [21]=> float(3) [18]=> float(2) }

preferences:
119.59 ms | 407 KiB | 5 Q