在foreach中,isLastItem()是否存在? [英] in foreach, isLastItem() exists?
问题描述
foreach
时是否有类似的情况?我的意思是这样的。 foreach($ array as $ item){
//做东西
//然后检查if我们在循环的最后一个迭代
$ last_iteration = islast(); //布尔真/假
}
如果没有,至少有一种方法知道当前迭代的当前索引,比如 $ iteration = 5
,所以我可以手动比较它的长度 $ array
您可以使用 SPL 的 ArrayIterator 和 CachingIterator class 拥有一个 hasNext
方法:
$ b $ pre $ $ iter = new CachingIterator(new ArrayIterator($ arr)) ;
foreach($ iter as $ value){
$ last_iteration =!$ iter-> hasNext();
}
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
}
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
?
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()是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!