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?
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?
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']);
}
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'];
}
For a long time:
mysql
API has been obsolete andmysqli
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']
);
}
© 2022 - 2024 — McMap. All rights reserved.
$counter
variable? – Ichneumon