Lovelock
Lovelock

Reputation: 8085

In a PHP foreach, assign a variable with that rows order number in the result

I have a basic blogging system with many users / blogs and then each blog has many posts.

I want to be able to number each of the posts from each blog e.g. #1 #2 #3 #4.

I echo out the posts in a foreach like so:

SELECT * FROM posts WHERE blogID = :blogID ORDER BY dateposted DESC

foreach:

    $postcontent = $row['postcontent'];

    echo "<div>$postcontent</div>";

endforeach

That works fine, but what i want is to be able to say:

    echo "<div>$postNumber, $postcontent</div>";

I cant just do:

$postNumber = $row['ID'];

As all of the posts are in one table so the ids are not relevant in that sense.

How can i assign a variable with an increasing number (starting from 1) and give that to each foreach item.

Thanks!

Upvotes: 0

Views: 324

Answers (2)

Amuchow
Amuchow

Reputation: 29

I believe that you could make a counter variable and then just increment it after each echo statement

Upvotes: 0

Barmar
Barmar

Reputation: 781503

Increment the variable directly in your code:

$postNumber = 1;
foreach: 
    $postcontent = $row['postcontent'];
    echo "<div>$postNumber, $postcontent</div>";
    $postNumber++;
endforeach

Upvotes: 3

Related Questions