I'm having a problem writing a suitable while loop logic in php, here is my code:
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br><hr />";
$counter = $items;
while($counter > 0){
if ($forquan / $items > 1){
print "we need 1 $autoadd<br>";
}
$counter--;
}
}
Now what i want is to add one additional product $autoadd
if we have 1-3 Batteries, and 2 $autoadd
if we have 3-6 and so on.
I tried so many different combinations of while loops if statements etc, but i cant seem to get the perfect loop.
You can simply calculate the number of required products and then iterate over that number:
<?php
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>
";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br>
<hr />
";
$countAddProducts = ceil($items / $forquan);
for ($i=0; $i<$countAddProducts; $i++) {
print "we need 1 $autoadd<br>
";
}
}
The loops output then is n
times the string "we need 1 Power Inverter", where n
is the rounded up value of $items
divided by $forquan
.
<?php
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br><hr />";
while($items > 0){
echo abs($forquan/$items); #check abs value
if (abs($forquan/$items) > 1){
print "we need 1 $autoadd<br>";
}
$items--;
}
}
?>