问题是你正在使用next($images)
在一个foreach ($images ...)
语句,从而修改内部数组指针。这可能会导致意外的行为,正如指出的foreach 的文档 http://www.php.net/foreach:
As foreach依赖于内部数组指针,在循环内更改它可能会导致意外的行为。
这说明了你的问题,使用foreach
and next
:
$images = array('one', 'two', 'three', 'four');
foreach ($images as $image) {
$next = next($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => three
two => four
three =>
four =>
人们可能会认为只需更换next()
with current()
会有所帮助,但可惜的是:
foreach ($images as $image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => two
three => two
four => two
根据评论foreach
文档页面,该页面上曾经有一条通知,指出:
除非数组被引用,foreach对指定数组的副本而不是数组本身进行操作。foreach对数组指针有一些副作用。不要在 foreach 期间或之后依赖数组指针而不重置它。
不知道为什么它被删除,但如果我们使用参考$image
然后它实际上起作用了(注意&
):
foreach ($images as &$image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
但也许老式的 for 循环更有意义:
for ($i = 0; $i < count($images); $i++) {
$nextIndex = $i + 1;
$next = ($nextIndex < count($images)) ? $images[$nextIndex] : null;
$image = $images[$i];
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
PHP 5.5.20 的输出。