How to get the next element in a PHP foreach

Asked

Viewed 3,553 times

2

How do I get the next element of an array using foreach?

For example, I am iterating in an array and I need to know if the next element of this array is equal to what I’m doing to do some operation with respect to this.

  • Dude, what do you mean? Explain better what the case is.

  • For example, I am iterating in an array and I need to know if the next element of this array is equal to what I’m doing to do some operation with respect to this.

  • Ah OK, I’ll modify my answer! :)

  • 1

    I’d use a for instead of the foreach. Then you do: for ($i=0; $i<$numero_elements_do_array) { if ($array[$i] == $array[$i+1]) { commands you want;} } But, put it further, you should post the real problem. 'Cause the way you posted it There’s no way of knowing if it would work.

  • You are talking about numerical arrays, associative arrays, or both?

  • Good question bfavareta, but if it uses a foreach, I think it uses an associative array. So, "need to read array[$i+1]" is not right.

Show 1 more comment

4 answers

5


php has an internal library called SPL (Standard PHP Library)

It has several objects and interfaces that help solve common problems that we find.

We have several Iterators to solve your problem, two in particular: ArrayIterator and CachingIterator

The ArrayIterator creates an object from an array with methods for functions such as current, next, rewind, etc..

Already the CachingIterator is an iterator with "one eye on the fish and one eye on the cat", having a forward position in relation to the iterator.

Within the foreach your code would look like this:

<?php

$arr = [
    'eu'    => 'tenho', 
    'sou'   => 'keys',
    'um'    => 'para',
    'array' => 'comparar',
    'assoc' => 'galera'
];

$iterator = new CachingIterator(new ArrayIterator($arr));

var_dump($iterator->current());                      // null
var_dump($iterator->getInnerIterator()->current());  // string(5) "tenho"

foreach($iterator as $key => $value){

    echo "Atual: $value - ";

    $proximoValue = $iterator->getInnerIterator()->current();
    echo "Proximo: $proximoValue \n";

    // Sua lógica aqui

}

2

Simple.

You do the normal foreach, but also use a next in the array to always pass to the next.

<?php

// Array
$itens = array('foot', 'bike', 'car', 'plane');

// Lista array completo
echo "Array completo: <b>".implode(',',$itens)."</b><br /><br />";

// Percorre o array
foreach($itens as $item){
    // Exibe o item atual baseado no foreach
    echo "Item atual: <b>".$item."</b> - ";

    // Exibe o próximo item
    echo "Item Proximo: <b>".current($itens)."</b><br />";
    next($itens);
}

?>

He will return.

Array completo: foot,bike,car,plane

Item atual: foot - Item Proximo: bike
Item atual: bike - Item Proximo: car
Item atual: car - Item Proximo: plane
Item atual: plane - Item Proximo: 

2

With the foreach may not be the best solution, but you can do with the each(), which returns the current element and moves the pointer forward an element. It would look like this:

$arr = array("a","b","c","c","d");


while($a= each($arr)){

    //o each() avançou um e guardou o anterior
    $b = current($arr);


    if($a['value'] == $b)
    {
        echo "OK<br>";
    }
    else
    {
        echo "NOT OK<br>"; 
    }
}

A look at the manual can help you understand better http://php.net/manual/en/function.each.php

0

Using a basic array, there is no difficulty (you need to read the index $x and $x+1). But with an associative array (what I think and the case here) and a bit more complicated. After searching, here is an answer:

<?php
$tab["A"] = 12;
$tab["B"] = 15;
$tab["C"] = 8;
$tab["D"] = 23;


foreach($tab as $key => $value)
{
    echo "Key e valor desta vez: ".$key. "-" .$value."<br>";

    $key =  key($tab);   // proximo index
    $val = $tab[$key];   // valor
    next($tab);          // avancar

    echo "Key e valor a proxima vez: ".$key."-".$val."<br><br>";
}
?>

The strange point and that needs to put the next() if not, we are each time with the same "next", as if we had 2 index (one for the foreach and one for the key).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.