Last active
January 18, 2024 13:30
-
-
Save davisngl/2aff548b5cf9615d42dc476859292186 to your computer and use it in GitHub Desktop.
Next item aware iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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