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

chc*_*ist 45 php foreach

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

提前致谢

Ste*_*hen 34

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

$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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


小智 20

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

while ($current = current($array) )
{
    $next = next($array);
    if (false !== $next && $next == $current)
    {
        //do something with $current
    }
}
Run Code Online (Sandbox Code Playgroud)


TML*_*TML 11

正如php.net/foreach指出:

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

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


Mār*_*dis 8

如果索引是连续的:

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

  • @EduardoRomero是的,这就是为什么我提到:`如果索引是连续的' (14认同)
  • 这不是真的,请尝试:array(1 =>'a',0 =>'b',100 =>'c'); (2认同)

And*_*ski 7

您可以获得键/值和索引

<?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";
}
Run Code Online (Sandbox Code Playgroud)

结果:

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 = ( => )
Run Code Online (Sandbox Code Playgroud)

  • 好一个!使用字符串作为键 (2认同)
  • 很棒的解决方案,因为每个人都应该拥有 PHP 7.0+ (2认同)

小智 5

如果其数字索引为:

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

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