How can I add an element to the beginning of array without changing array key values in PHP?
To keep numerical keys from being reindexed, you could simply add the arrays together.
Instead of:
array_unshift($arr1, $arr2)
try:
$arr1 = $arr2 + $arr1;
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?
EDIT:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With