Roger
Roger

Reputation: 238

PHP For loop, Print specifc no of times

I want to loop and echo images specific value, I have a db value e.g 100, but i want to echo only 96 images only not more than that. Also whatever the value from DB and loop should print the exact times not exceeding 96(which is fixed)

$check = "SELECT white FROM balloons";
$rs = mysqli_query($con,$check);
if(mysqli_num_rows($rs)==1)
{
$row = mysqli_fetch_assoc($rs);
$g=$row['white']; //eg 2,

for($imagecount=0;$imagecount>$g;$imagecount++) {
echo '<img src="img/whiteB.png" class="w_over" />';
}
}

Upvotes: 0

Views: 71

Answers (4)

Error in for loop condition!

change for loop head:

for($imagecount=0;$imagecount<$g;$imagecount++)

Upvotes: 0

MBaas
MBaas

Reputation: 7530

I'd change

for($imagecount=0;$imagecount>$g;$imagecount++) {

to

for($imagecount=0;$imagecount<=min($g,96);$imagecount++) {

Pls. note that the 2nd param in for needs to inverted (loop while condition is true)

Upvotes: 1

Michael Freund
Michael Freund

Reputation: 234

for ($i=0; $i < min($g, 96); $i++) {
  echo '<img src="img/whiteB.png" class="w_over" />';
}

Upvotes: 2

Rikesh
Rikesh

Reputation: 26421

If i get your question correctly you just need to change your line,

$g=$row['white'];

to:

$g = ($row['white'] < 96) ? $row['white'] : 96;

Side Note:

 for($imagecount = 0; $imagecount < $g; $imagecount++) //Should be less then
                                  ^

Upvotes: 1

Related Questions