使用常规的for循环,可以将当前索引与最后一个一起进行comapred,以判断我是否在循环的最后一次迭代中.使用时有类似的东西foreach吗?我的意思是这样的.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
Run Code Online (Sandbox Code Playgroud)
如果没有,至少有一种方法可以知道当前迭代的当前索引$iteration = 5,所以我可以手动将它与长度相比较$array?
awm*_*awm 21
计数器方法可能是最简单的方法.
$i = count($array);
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = !(--$i); //boolean true/false
}
Run Code Online (Sandbox Code Playgroud)
Gum*_*mbo 13
您可以使用SPL的ArrayIterator和CachingIterator类的组合来获得一个hasNext方法:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
Run Code Online (Sandbox Code Playgroud)