How to get the next element in a foreach in PHP

2

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

For example, I'm iterating in an array and I need to know if the next element in this array is the same as what I'm about to do some operation against it.

    
asked by anonymous 16.10.2014 / 01:59

4 answers

5

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

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

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.

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

Within 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

}
    
16.10.2014 / 13:11
2

With foreach it may not be the best solution, but you can do with each() , which returns the current element and advances the pointer 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 better understand link

    
16.10.2014 / 13:05
2

Simple.

You make the foreach normal, but also use a next in the array to always move 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);
}

?>

It 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: 
    
16.10.2014 / 15:58
0

Using a basic array, you have 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 little 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>";
}
?>

    
16.10.2014 / 02:16