1

I have a sql query that is returning me rows like this:

ID | Code | Numb 1 | 1 | 1 2 | 2 | 2 3 | 3 | 3

and I am trying to write foreach loop that will always show the previous values.

My normal foreach loop like this:

foreach($array as $key => $val) { echo '$val['code']; }

how can i make the value to always be from the previous row?

4
  • 1
    What's your expected output? The question is not clear as not sure why you would want to do this. Commented Jan 14, 2018 at 9:14
  • the loop always with zero, if you want specific value before key, we can get Commented Jan 14, 2018 at 9:15
  • my goal is when the loop is echoing the second code which is 2 it should be 1 @LawrenceCherone then the third code will be 2 Commented Jan 14, 2018 at 11:21
  • Then you should accept @Sohel0415 answer as it does exactly that (though a little untidy). Commented Jan 14, 2018 at 11:36

1 Answer 1

1

You could kept your old value to a variable and use it at the next iteration. And as @Daniel notices, you need to check that variable defined or not by using isset().

foreach($array as $key => $val) {
  if(isset($prev)) 
     echo $prev;
  $prev = $val['code'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

First time echo $prev; is undefined. You should check it if(isset($prev)) echo $prev;
You would have to echo once more outside of the loop for the final item.
@Matt Yes, If he needs, he should, I just consider the previous data part
@Sohel0415, I have tried and it worked fine .. thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.