Skip to content

Instantly share code, notes, and snippets.

@davisngl
Last active January 18, 2024 13:30
Show Gist options
  • Save davisngl/2aff548b5cf9615d42dc476859292186 to your computer and use it in GitHub Desktop.
Save davisngl/2aff548b5cf9615d42dc476859292186 to your computer and use it in GitHub Desktop.
Next item aware iterator
<?php
$collection = collect(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']);
$iterator = $collection->getIterator();
foreach ($iterator as $item) {
$iterator->next();
// Next item in collection. Before doing anything with it
// should check if the "next" one is not null.
$next = $iterator->current();
if ($iterator->key() > 0) {
// Put interal pointer to previous item, as next "current" one will skip 1 item, as in every non-first
// loop internal pointer already gets moved one position forward.
$iterator->seek($iterator->key() - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment