I am looking for a way to get the next and next+1 key/value pair in a foreach(). For example:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
foreach($a AS $k => $v){
if($nextval == $v && $nextnextval == $v){
//staying put for next two legs
}
}
Here we discuss two methods to find duplicate values in array using PHP foreach loop, Using array_search()function and foreach loop. Using two foreach loops. In this process, first, we create an associative array with static values, then we do both operations where we use foreach loop.
The foreach loop - Loops through a block of code for each element in an array. The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
If you would like to access both key and value of key-value pairs in array with foreach, use the following syntax foreach (array_expression as $key => $value) { statement (s) } Now, you can access both key and value using variable $key and $value variables respectively. Example – foreach on Array of Integers
PHP Array foreach is a construct in PHP that allows to iterate over arrays easily. In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios foreach loop to iterate over PHP array of numbers.
I've found the solution with complexity O(n)
and does not require seeking through array back and forward:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
// initiate the iterator for "next_val":
$nextIterator = new ArrayIterator($a);
$nextIterator->rewind();
$nextIterator->next(); // put the initial pointer to 2nd position
// initiaite another iterator for "next_next_val":
$nextNextIterator = new ArrayIterator($a);
$nextNextIterator->rewind();
$nextNextIterator->next();
$nextNextIterator->next(); // put the initial pointer to 3rd position
foreach($a AS $k => $v){
$next_val = $nextIterator->current();
$next_next_val = $nextNextIterator->current();
echo "Current: $v; next: $next_val; next_next: $next_next_val" . PHP_EOL;
$nextIterator->next();
$nextNextIterator->next();
}
Just remember to test for valid()
if you plan to relay on the $next_val
and $next_next_val
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With