Bob
Bob

Reputation: 177

Maintain a counter while looping a query result set

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?

Upvotes: 6

Views: 41913

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

For a long time:

  • the mysql API has been obsolete and
  • the mysqli API's result set object has been traversable via foreach() as if an array of associative rows.

Instead of maintaining the counter manually, just access the index that the foreach() provides.

Code: (Demo)

$sql = <<<SQL
SELECT *
FROM your_table
ORDER BY lastname, firstname
SQL;

foreach ($mysqli->query($sql) as $i => $row) {
    printf(
        "<div>%d: %d, %s, %s</div>\n",
        $i + 1,
        $row['id'],
        $row['firstname'],
        $row['lastname']
    );
}

Upvotes: 0

GordonM
GordonM

Reputation: 31730

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']);
}

Upvotes: 21

Daniel Freudenberger
Daniel Freudenberger

Reputation: 352

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'];
}

Upvotes: 17

Related Questions