Nabil Ali - 5 months ago 28

PHP Question

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`

`$autoadd`

I tried so many different combinations of while loops if statements etc, but i cant seem to get the perfect loop.

Answer

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>\n";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br>\n<hr />\n";
$countAddProducts = ceil($items / $forquan);
for ($i=0; $i<$countAddProducts; $i++) {
print "we need 1 $autoadd<br>\n";
}
}
```

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`

.