December 23rd, 2012, 08:27 AM

Calculate how many times a number fits in another
Hi guys,
First of all, happy holidays
What is the cleanest way to calculate how many times a number fits into another number with PHP?
For example, my script will have 2 variable numbers let's say: 14 and 33. So 14 will fit twice in 33.
What is the best way to calculate this? I also need to know how much remains.
I was thinking of doing this in a loop, but that doesnt seem optimal.
Any thoughts?
December 23rd, 2012, 08:56 AM

December 23rd, 2012, 09:04 AM

Hi,
this is called integer division. Unfortunately, PHP doesn't have that built in, so you have to write it yourself:
PHP Code:
echo (int) (33/14);
(Using round() or floor() yields the incorrent result for negative numbers).
The remainder is calculated with the % operator:
December 23rd, 2012, 11:03 AM

Thanks guys. Im building an online shop for dutch holiday foods, with special deals on large quantities (bags).
But these bags can have variable quantities in them. So lets say we have this:
Bag of 20
Bag of 10
And a order quantity of 32. The bag of 20 fits in once and the bag of 10 fits in once, and we'd have 3 single ones left. I was thinking of coding it like this:
PHP Code:
<?php
$amount = 33; //Variable
$product_id = 1; //Variable
$discount_query = dbquery("SELECT * FROM products WHERE product_sub='1' AND product_subid='".$product_id."' AND product_mq<='".$amount."' ORDER BY product_mq DESC"); //Select the discount bags from the database
while($discount_data = dbarray($discount_query)){ //Loop through bags, from high quantity to low
//$total = (int) ($a / $b);
$discountbags[$discount_data['product_id']] = (int) ($amount / $discount_data['product_mq']); //Count how many wholesale bags of the current type and product id fit in the current amount
$amount = ($amount % $discount_data['product_mq']); //Update the amount for the next iteration
}
print_r $discountbags; //How many wholesale bags of different types fit in the current amount
?>
I havent tested it yet since my system is pretty complicated, but would this be a correct way to do it?
Last edited by Rhytz; December 23rd, 2012 at 11:06 AM.