Allows iteration over an array but returns two items at a time stepping by one item at a time. Thus, the iterator for
['a', 'b', 'c', 'd']
Will return
['previous' => 'a', 'current' => 'b']
['previous' => 'b', 'current' => 'c']
['previous' => 'c', 'current' => 'd']
Allows iteration over an array but returns two items at a time stepping by one item at a time. Thus, the iterator for
['a', 'b', 'c', 'd']
Will return
['current' => 'a', 'next' => 'b']
['current' => 'b', 'next' => 'c']
['current' => 'c', 'next' => 'd']
['current' => 'd', 'next' => null]
To install it, just include this requirement into your composer.json
{
"require": {
"crazycodr/previous-current-iterator": "1.*"
}
}
And then run composer install/update as necessary.
Only PHP 5.5 or more can be supported due to the fact that key() can only return arrays starting with PHP 5.5!
To use the PreviousCurrentIterator, just instanciate a copy with an array and foreach it!
$data = ['a', 'b', 'c', 'd'];
foreach(new PreviousCurrentIterator($data) as $keys => $values) {
//Compare previous and current
if ($values['previous'] !== $values['current']) {
echo 'Not the same<br />';
}
}
To use the CurrentNextIterator, just instanciate a copy with an array and foreach it!
$data = ['a', 'b', 'c', 'd'];
foreach(new CurrentNextIterator($data) as $keys => $values) {
//Compare previous and current
if ($values['next'] !== null) {
if ($values['current'] !== $values['next']) {
echo 'Not the same<br />';
}
}
}
Practical if you need to compare two items together in a previous vs current or current vs next manner.