添加到数组的开头元素,而不改变其他数组键 [英] Adding an element to the beginning of an array without changing other array keys

查看:148
本文介绍了添加到数组的开头元素,而不改变其他数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加到数组的开头,一个元素没有在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆