Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlindsey's avatar

How to iterate a collection and have access to preceding item within the loop

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?

0 likes
1 reply
jeffreyvanrossum's avatar

Something like this perhaps?

collect([1,2,3])->each(function ($item, $key) use ($collection) {
    $previous = $collection[$key-1] ?? null;
    //
});

Please or to participate in this conversation.