Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easier way to get counter from while loop?

Tags:

php

while-loop

I have the following:

$counter = 1;   
while($row= mysql_fetch_assoc($result)) {
    $counter2 = $counter++;

    echo($counter2 . $row['foo']);
}

Is there an easier way to get 1,2,3 etc for each result or is this the best way?

Thanks

like image 955
Bob Avatar asked May 22 '11 10:05

Bob


1 Answers

You don't need $counter2. $counter++ is fine. You can even do it on the same line as the echo if you use preincrement instead of postincrement.

$counter = 0;   
while($row= mysql_fetch_assoc($result)) {
    echo(++$counter . $row['foo']);
}
like image 73
GordonM Avatar answered Sep 24 '22 09:09

GordonM