我有一个 foreach 循环,我想查看循环中是否有下一个元素,以便我可以将当前元素与下一个元素进行比较。我怎样才能做到这一点?我已阅读有关当前和下一个功能的信息,但我不知道如何使用它们。
一种独特的方法是反转数组并then环形。这也适用于非数字索引数组:
$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;
}
如果您仍然有兴趣使用current
and next
函数,你可以这样做:
$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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)