問題描述
使用常規的 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 的 >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() 存在嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!