PHP - Packing widgets into the fewest number of boxes, plus minimum order quantity
OK, I agree that this is a bit harder than I assumed yesterday. You basically have two opposing demands: 


No more widgets than necessary should be sent. 
The fewest packs possible should be sent.


You cannot fulfill both. So if I tried to send 1200 widgets, rule 2 says I should send a pack of 2000, however, rule 1 says I should send 2 packs: one of 1000 and one of 250. Which rule should prevail?

I chose that rule 1 should prevail in the solution below. The reason is that no customer wants more widgets than absolutely necessary.

$packSizes = [ 250,
               500,
              1000,
              2000,
              5000];

function optimizePacks($packSizes,$number)
{
    rsort($packSizes);
    $requiredPacks = array_fill_keys($packSizes,0);
    foreach ($packSizes as $size) {
        $packs = floor($number/$size);
        if ($packs &gt; 0) {
            $requiredPacks[$size] = $packs;
            $number -= $packs*$size;
        }
    }
    if ($number &gt; 0) $requiredPacks[min($packSizes)]++;
    return $requiredPacks;
}

$packs = optimizePacks($packSizes,6666);

print_r($packs);


This will work for any array of pack sizes and any number of widgets. The output of this code is:


  Array (
      [5000] => 1
      [2000] => 0
      [1000] => 1
      [500] => 1
      [250] => 1 )


Which is one pack more than rule 2 would demand (one of 5000 and two of 1000). It would, of course, be possible to let rule 2 prevail, but I cannot fulfill both rules.