我正在使用 foreach 循环关联数组。我希望能够检查正在处理的键值对是否是最后一个,以便我可以对其进行特殊处理。有什么想法我可以如何以最好的方式做到这一点?
foreach ($kvarr as $key => $value){
// I'd like to be able to check here if this key value pair is the last
// so I can give it special treatment
}
最佳答案
就这么简单,没有计数器和其他“黑客”。
foreach ($array as $key => $value) { // your stuff if (next($array) === false) { // this is the last iteration } }
请注意,您必须使用 ===
,因为函数 next()
可能会返回一个非 bool 值,该值计算结果为 false
,例如0
或“”(空字符串)。
关于php - 查找关联数组中的最后一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1651569/