在数组迭代期间检查当前元素是否是最后一个元素
请帮我将此伪代码翻译为真正的 php 代码:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
编辑:数组可能有数字或字符串键
Please help me to translate this pseudo-code to real php code:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
Edit: the array may have numerical or string keys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用 PHP 的 end()
Update1
正如 @Mijoja 所指出的如果数组中多次具有相同的值,上面可能会出现问题。下面是它的修复方法。
更新2
我发现@onteria_的解决方案比我回答的更好,因为它不会修改数组内部指针,我正在更新答案以匹配他的答案。
谢谢@onteria_
Update3
正如@CGundlach指出的那样 PHP 7.3 引入了
array_key_last
如果您使用 PHP >= 7.3,这似乎是更好的选择you can use PHP's end()
Update1
as pointed out by @Mijoja the above could will have problem if you have same value multiple times in array. below is the fix for it.
Update2
I found solution by @onteria_ to be better then what i have answered since it does not modify arrays internal pointer, i am updating the answer to match his answer.
Thank you @onteria_
Update3
As pointed by @CGundlach PHP 7.3 introduced
array_key_last
which seems much better option if you are using PHP >= 7.3这总是对我有用
编辑 30/04/15
以避免 @Warren Sergent 提到的 E_STRICT 警告
This always does the trick for me
Edit 30/04/15
To avoid the E_STRICT warning mentioned by @Warren Sergent
由于
array_pop
作用于由array_keys
创建的临时数组,因此它根本不会修改原始数组。Since
array_pop
works on the temporary array created byarray_keys
it doesn't modify the original array at all.为什么不采用这个非常简单的方法:
Why not this very simple method:
我知道这已经很旧了,使用 SPL 迭代器可能有点矫枉过正,但无论如何,这里有另一个解决方案:
I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:
我的解决方案,也很简单..
My solution, also quite simple..
如果项目按数字排序,请使用 key() 函数确定当前项目的索引并将其与长度进行比较。您必须使用 next() 或 prev() 在 while 循环而不是 for 循环中循环遍历项目:
If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:
使用
array_keys
函数获取键的简单方法,并仅获取反向数组的第一个键[0]
,这是最后一个键< /em>.注意:
array_reverse
反向数组采用两个参数,第一个参数是我们想要反转的数组,第二个参数是true,用于反转数组并保留键的顺序 。Simple approach using
array_keys
function to get the keys and get only first key[0]
of reversed array which is the last key.NOTE:
array_reverse
reverse array take two arguments first array we want be reversed and second parameter true, to reverse the array and preserves the order of keys.