easier way to get counter from while loop?

前端 未结 2 1442
广开言路
广开言路 2020-12-19 09:44

I have the following:

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

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


        
相关标签:
2条回答
  • 2020-12-19 10:09

    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']);
    }
    
    0 讨论(0)
  • 2020-12-19 10:31

    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'];
    }
    
    0 讨论(0)
提交回复
热议问题