Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an element to the beginning of an array without changing other array keys [duplicate]

Tags:

arrays

php

How can I add an element to the beginning of array without changing array key values in PHP?

like image 397
mTuran Avatar asked Sep 08 '25 12:09

mTuran


2 Answers

To keep numerical keys from being reindexed, you could simply add the arrays together.

Instead of:

array_unshift($arr1, $arr2)

try:

$arr1 = $arr2 + $arr1;
like image 198
Kevin Wentworth Avatar answered Sep 11 '25 03:09

Kevin Wentworth


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.

like image 21
Martin Hennings Avatar answered Sep 11 '25 03:09

Martin Hennings