in foreach, isLastItem() exists?(在 foreach 中,isLastItem() 存在吗?)
问题描述
使用常规的 for 循环,可以将当前索引与最后一个进行比较,以判断我是否处于循环的最后一次迭代中.使用 foreach
时是否有类似的事情?我的意思是这样的.
Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach
? I mean something like this.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
如果没有,是否至少有一种方法可以知道当前迭代的当前索引,例如 $iteration = 5
,以便我可以手动将其与 $array 的长度进行比较
?
If not, is there at least a way to know the current index of the current iteration like $iteration = 5
, so I can manually compare it to the length of the $array
?
推荐答案
您可以组合使用 SPL 的 href="http://php.net/class.arrayiterator">ArrayIterator 和 CachingIterator 类有一个 hasNext
方法:
You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext
method:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
这篇关于在 foreach 中,isLastItem() 存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 foreach 中,isLastItem() 存在吗?


基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- HTTP 与 FTP 上传 2021-01-01