将元素添加到数组的开头而不更改其他数组键 [英] Adding an element to the beginning of an array without changing other array keys
问题描述
如何在不改变 PHP 中数组键值的情况下将元素添加到数组的开头?
How can I add an element to the beginning of array without changing array key values in PHP?
推荐答案
如果您使用自分配(例如文字)键,array_unshift() 会做到.
如果您使用自动生成的(数字)键,那应该如何工作?使用-1"作为新的第一个键?
If you use self-assigned (e.g. literal) keys, array_unshift() will do it.
If you use auto-generated (numeric) keys, how should that work? Use '-1' as the new first key?
感谢 JasonS 指出此答案中的错误.
任何数字键都将被 array_unshift()
重新索引,无论它是自动生成的还是自分配的——如果它是数字键,它就会被打乱.有关详细信息,请参阅上述文档的链接.
Thank you to JasonS for pointing out an error in this answer.
ANY numeric key will be re-indexed by array_unshift()
, no matter if it was auto-generated or self-assigned - if it's numeric, it'll get scrambled. See the link to the documentation above for details.
这篇关于将元素添加到数组的开头而不更改其他数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!