Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array get next key/value in foreach() [duplicate]

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
    }

}
like image 716
danielb Avatar asked Dec 09 '13 20:12

danielb


People also ask

How to find duplicate values in array using PHP foreach loop?

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.

What is a foreach loop in PHP?

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.

How to access key and value in array with foreach?

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

How to iterate over array of numbers in PHP?

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.


1 Answers

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.

like image 192
Maciej Sz Avatar answered Oct 09 '22 11:10

Maciej Sz