Get next element in foreach loop(获取 foreach 循环中的下一个元素)
问题描述
我有一个 foreach 循环,我想查看循环中是否有下一个元素,以便我可以将当前元素与下一个元素进行比较.我怎样才能做到这一点?我已经阅读了 current 和 next 函数,但我不知道如何使用它们.
I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I've read about the current and next functions but I can't figure out how to use them.
提前致谢
推荐答案
一种独特的方法是反转数组和 then 循环.这也适用于非数字索引数组:
A unique approach would be to reverse the array and then loop. This will work for non-numerically indexed arrays as well:
$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
和 next
函数感兴趣,您可以这样做:
If you are still interested in using the current
and next
functions, you could do this:
$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;
#2 is probably the best solution. Note, $i < $length - 1;
will stop the loop after comparing the last two items in the array. I put this in the loop to be explicit with the example. You should probably just calculate $length = count($items) - 1;
这篇关于获取 foreach 循环中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取 foreach 循环中的下一个元素


- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01