Home » Php » php – Auto increment variable in while loop

php – Auto increment variable in while loop

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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;

Answer:

First off, you will have to declare the index variable before the while loop.
If you declare it inside, it will be a new variable each time it iterates.
When that is done, you will need to increment the variable for each iteration, this can be done by either $i++ or $i+=1.

If you wish it to start with 1 and the increase, set it to 1 from start and increase it by 1 at the end of the loop.

Like:

$index = 1;
while(...) {
  // Do stuff...
  $index++; // increase.
}

Answer:

Initialize the variable by $i=1 like:

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

echo $i; // will print 1,2,3 to number of count.
$i++;
}

Answer:

$i = 0;
while ($i < $row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $i++;
} 
echo $i;