在foreach循环中获取下一个元素

时间:2011-02-23 20:38:39

标签: php foreach

我有一个foreach循环,我想看看循环中是否有下一个元素,所以我可以将当​​前元素与下一个元素进行比较。我怎样才能做到这一点?我已经阅读了当前和下一个功能,但我无法弄清楚如何使用它们。

提前致谢

9 个答案:

答案 0 :(得分:31)

一种独特的方法是反转数组和然后循环。这也适用于非数字索引的数组:

$items = array(
    'one'   => 'two',
    'two'   => 'two',
    'three' => 'three'
);
$backwards = array_reverse($items);
$last_item = NULL;

foreach ($backwards as $current_item) {
    if ($last_item === $current_item) {
        // they match
    }
    $last_item = $current_item;
}

如果您仍然对使用currentnext函数感兴趣,可以这样做:

$items = array('two', 'two', 'three');
$length = count($items);
for($i = 0; $i < $length - 1; ++$i) {
    if (current($items) === next($items)) {
        // they match
    }
}

#2可能是最好的解决方案。注意,$i < $length - 1;将在比较数组中的最后两项后停止循环。我把它放在循环中以显示示例。您应该只计算$length = count($items) - 1;

答案 1 :(得分:14)

您可以使用while循环而不是foreach:

while ($current = current($array) )
{
    $next = next($array);
    if (false !== $next && $next == $current)
    {
        //do something with $current
    }
}

答案 2 :(得分:10)

正如php.net/foreach所指出的那样:

  

除非引用了数组,否则foreach将对指定数组的副本进行操作,而不是对数组本身进行操作。 foreach对数组指针有一些副作用。不要在foreach期间或之后依赖数组指针而不重置它。

换句话说 - 做你要做的事并不是一个好主意。或许最好与某人讨论你为什么要这样做,看看是否有更好的解决方案?如果您没有任何其他可用资源,请随时在irc.freenode.net上的## PHP中询问我们。

答案 3 :(得分:7)

如果索引是连续的:

foreach ($arr as $key => $val) {
   if (isset($arr[$key+1])) {
      echo $arr[$key+1]; // next element
   } else {
     // end of array reached
   }
}

答案 4 :(得分:4)

如果用数字索引:

foreach ($foo as $key=>$var){

    if($var==$foo[$key+1]){
        echo 'current and next var are the same';
    }
}

答案 5 :(得分:3)

一般解决方案可以是缓存迭代器。正确实现的缓存迭代器可以与任何迭代器一起使用,并节省内存。 PHP SPL有CachingIterator,但它很奇怪,功能非常有限。但是,您可以编写自己的前瞻迭代器,如下所示:

<?php

class NeighborIterator implements Iterator
{

    protected $oInnerIterator;

    protected $hasPrevious = false;
    protected $previous = null;
    protected $previousKey = null;

    protected $hasCurrent = false;
    protected $current = null;
    protected $currentKey = null;

    protected $hasNext = false;
    protected $next = null;
    protected $nextKey = null;

    public function __construct(Iterator $oInnerIterator)
    {
        $this->oInnerIterator = $oInnerIterator;
    }

    public function current()
    {
        return $this->current;
    }

    public function key()
    {
        return $this->currentKey;
    }

    public function next()
    {
        if ($this->hasCurrent) {
            $this->hasPrevious = true;
            $this->previous = $this->current;
            $this->previousKey = $this->currentKey;
            $this->hasCurrent = $this->hasNext;
            $this->current = $this->next;
            $this->currentKey = $this->nextKey;
            if ($this->hasNext) {
                $this->oInnerIterator->next();
                $this->hasNext = $this->oInnerIterator->valid();
                if ($this->hasNext) {
                    $this->next = $this->oInnerIterator->current();
                    $this->nextKey = $this->oInnerIterator->key();
                } else {
                    $this->next = null;
                    $this->nextKey = null;
                }
            }
        }
    }

    public function rewind()
    {
        $this->hasPrevious = false;
        $this->previous = null;
        $this->previousKey = null;
        $this->oInnerIterator->rewind();
        $this->hasCurrent = $this->oInnerIterator->valid();
        if ($this->hasCurrent) {
            $this->current = $this->oInnerIterator->current();
            $this->currentKey = $this->oInnerIterator->key();
            $this->oInnerIterator->next();
            $this->hasNext = $this->oInnerIterator->valid();
            if ($this->hasNext) {
                $this->next = $this->oInnerIterator->current();
                $this->nextKey = $this->oInnerIterator->key();
            } else {
                $this->next = null;
                $this->nextKey = null;
            }
        } else {
            $this->current = null;
            $this->currentKey = null;
            $this->hasNext = false;
            $this->next = null;
            $this->nextKey = null;
        }
    }

    public function valid()
    {
        return $this->hasCurrent;
    }

    public function hasNext()
    {
        return $this->hasNext;
    }

    public function getNext()
    {
        return $this->next;
    }

    public function getNextKey()
    {
        return $this->nextKey;
    }

    public function hasPrevious()
    {
        return $this->hasPrevious;
    }

    public function getPrevious()
    {
        return $this->previous;
    }

    public function getPreviousKey()
    {
        return $this->previousKey;
    }

}


header("Content-type: text/plain; charset=utf-8");
$arr = [
    "a" => "alma",
    "b" => "banan",
    "c" => "cseresznye",
    "d" => "dio",
    "e" => "eper",
];
$oNeighborIterator = new NeighborIterator(new ArrayIterator($arr));
foreach ($oNeighborIterator as $key => $value) {

    // you can get previous and next values:

    if (!$oNeighborIterator->hasPrevious()) {
        echo "{FIRST}\n";
    }
    echo $oNeighborIterator->getPreviousKey() . " => " . $oNeighborIterator->getPrevious() . " ----->        ";
    echo "[ " . $key . " => " . $value . " ]        -----> ";
    echo $oNeighborIterator->getNextKey() . " => " . $oNeighborIterator->getNext() . "\n";
    if (!$oNeighborIterator->hasNext()) {
        echo "{LAST}\n";
    }
}

答案 6 :(得分:2)

您可以在foreach之前获取数组的键,然后使用计数器检查下一个元素,如:

//$arr is the array you wish to cycle through
$keys = array_keys($arr);
$num_keys = count($keys);
$i = 1;
foreach ($arr as $a)
{
    if ($i < $num_keys && $arr[$keys[$i]] == $a)
    {
        // we have a match
    }
    $i++;
}

这适用于简单数组(例如array(1,2,3))和键控数组(例如array('first'=>1, 'second'=>2, 'thrid'=>3))。

答案 7 :(得分:1)

php中的foreach循环将迭代原始数组的副本,使next()prev()函数无效。如果你有一个关联数组并需要获取下一个项目,你可以改为迭代数组键:

foreach (array_keys($items) as $index => $key) {
    // first, get current item
    $item = $items[$key];
    // now get next item in array
    $next = $items[array_keys($items)[$index + 1]];
}

由于生成的键数组本身具有连续索引,因此您可以使用它来访问原始数组。

请注意最后一次迭代$nextnull,因为最后一次之后没有下一个项目。访问不存在的数组键将引发php通知。为避免这种情况,要么:

  1. 在将值分配给$next
  2. 之前检查最后一次迭代
  3. 检查index + 1的密钥是否与array_key_exists()
  4. 一起存在

    使用方法2,完整的foreach可能如下所示:

    foreach (array_keys($items) as $index => $key) {
        // first, get current item
        $item = $items[$key];
        // now get next item in array
        $next = null;
        if (array_key_exists($index + 1, array_keys($items))) {
            $next = $items[array_keys($items)[$index + 1]];
        }
    }
    

答案 8 :(得分:1)

您可以获取键/值和索引

<?php
$a = array(
    'key1'=>'value1', 
    'key2'=>'value2', 
    'key3'=>'value3', 
    'key4'=>'value4', 
    'key5'=>'value5'
);

$keys = array_keys($a);
foreach(array_keys($keys) as $index ){       
    $current_key = current($keys); // or $current_key = $keys[$index];
    $current_value = $a[$current_key]; // or $current_value = $a[$keys[$index]];

    $next_key = next($keys); 
    $next_value = $a[$next_key] ?? null; // for php version >= 7.0

    echo  "{$index}: current = ({$current_key} => {$current_value}); next = ({$next_key} => {$next_value})\n";
}

结果:

0: current = (key1 => value1); next = (key2 => value2) 
1: current = (key2 => value2); next = (key3 => value3) 
2: current = (key3 => value3); next = (key4 => value4) 
3: current = (key4 => value4); next = (key5 => value5) 
4: current = (key5 => value5); next = ( => )