6

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

Bob
  • 177
  • 1
  • 3
  • 11

2 Answers2

21

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']);
}
GordonM
  • 31,179
  • 15
  • 87
  • 129
  • 1
    Why did you get an upvote? You didn't show him his first error ($counter=2)? – Micromega May 22 '11 at 10:45
  • He was postincrementing $counter, so $counter2 would get the value of $counter before it gets incremented. This version is using preincrementing, so $counter would get the value 1 before it's echoed for the first time. – GordonM May 22 '11 at 17:56
  • thanks. I delete my answer although i was faster than you but nobody is upvote me. – Micromega May 22 '11 at 18:04
17

I know it's not exactly what you have asked for - but why don't you simply use a for-loop instead of while?

for ($i = 0; $row = mysql_fetch_assoc($result); ++$i) {
    echo $i . $row['foo'];
}