Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment variable in while loop

Tags:

html

php

I have a variable that is a string with divs in html.

I'm trying to include a number in it that starts at one and auto increments so that each div is numbered in ascending order.

This is my while:

while ($row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$catname9 = $row9["catname"];
$statusid9 = $row9["id"];
$i = 1;

This is my string that I echo repeatedly until it reaches the end of my called SQL table:

$list9 .= '<div id="each9" style="margin-top:3px" onclick="moveTo(\'.main\', '.$i.');"></div>

Then I echo:

<?php echo $list9; ?>

So how do I make the first one 1 then the second repeat 2 and the third repeat 3?

like image 652
peter Avatar asked Jun 07 '15 07:06

peter


People also ask

How do you increment a variable in a while loop?

Re: How do I increment a variable at the end of a loop to run it through the loop again? Add (or subtract) the iteration value and your number. If you want to increment or decrement by more than one you can multiply the iteration value and then add or subtract.

Can you increment in a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

Does python while loop auto increment?

The while loop in python is a way to run a code block until the condition returns true repeatedly. Unlike the "for" loop in python, the while loop does not initialize or increment the variable value automatically.


1 Answers

Set up your while loop like so:

$i = 1;
while ($row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

    // looped logic here

    $i++;
}

The important thing here is to initialize the counter before the loop, and increment it on each iteration.

You can also increment it by other amounts if you want. Just replace $i++ with $i += 2;

like image 115
Stuart Wagner Avatar answered Sep 24 '22 11:09

Stuart Wagner