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?
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.
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.
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.
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
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With