How do I retain a previous value from a foreach, MySQL PDO loop?

My data is in MySQL, I prefer to use PDO, so I loop through the results with:

foreach( $db->($sql) as $row ) {
    $previous = ????;
    $counter = $row[counter];

But I need to keep the previous value of $counter for testing in the next loop. I tried using this previous SO question,

Trying to get next and previous item in foreach loop in PHP in symfony?

but I don’t understand how to translate its solution to my issue. Can someone please show me.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I am not sure if I have undestood well. Do you mean this?

$previousCounter = 0;
foreach($db->($sql) as $row) {
    // here you can read $previousCounter value
    $counter = $row[counter];
   $previousCounter = $counter;

And if you want the full previous row:

// declare $previous
foreach($db->($sql) as $row) {
    // here you can read $previous value
    // not in the first iteration, but in all the others
    $counter = $row[counter];
    $previous = $row;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x