Level 9
Something like this perhaps?
collect([1,2,3])->each(function ($item, $key) use ($collection) {
$previous = $collection[$key-1] ?? null;
//
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a collection which looks a lot more complicated than this:
$c = collect([1,2,3])
But essentially I need a loop where I can access both the current item AND the previous one with each iteration. If there is no previous item null will be fine.
I know how to do this a couple of ways but they aren't pretty to look at. One way is to use an old-school for loop with indexes like $c[$i] and $c[$i-1] and the other is map over the collection and pass the item into an external $previous variable at the end of the loop callback.
Anybody know a better way to do this?
Please or to participate in this conversation.