6

I am looping through an array using foreach.

In a particular situation I need to know the value of the next element before iteration comes to that(like a prediction) element. For that I am planning to use the function next().

In documentation I just noticed that next() advances the internal array pointer forward.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

If so will it affect my foreach loop?

4

3 回答 3

10

如果您以这种方式使用它不会影响您的循环

<?php

$lists = range('a', 'f');

foreach($lists as &$value) {
   $next = current($lists);
   echo 'value: ' . $value . "\n" . 'next: ' . $next . "\n\n";
}

输出

值:a 下一个:b

值:b 下一个:c

值:c 下一个:d

值:d 下一个:e

值:e 下一个:f

值:f 下一个:

于 2013-07-31T06:10:28.800 回答
3

next() 影响foreach(),期间。

至少在 PHP 7.2 中,

$values = ['a', 'b', 'c', 'd', 'e'];

foreach ($values as $value) {
  next($values);
  $two_ahead = next($values);
  echo("Two ahead: $two_ahead\n");
  echo("Current value: $value\n");
}

产生:

Two ahead: c
Current value: a
Two ahead: e
Current value: b
Two ahead: 
Current value: c
Two ahead: 
Current value: d
Two ahead: 
Current value: e

另请注意,foreach 循环也不影响 next 的位置。他们是独立的。

如果您有一个带有顺序数字键的数组(默认值),那么ops 的答案最适合您尝试做的事情。我只是回答了这个问题。

于 2019-09-18T16:48:30.037 回答
1

试试这个代码:

$a=$array();
foreach($a as $key=>$var)
{
   if(isset($a[$key+1]))
      echo $a[$key+1];//next element
}
于 2013-07-31T06:10:10.460 回答