array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won’t be touched.
does not work for me. I also tried adding an array as the second argument of array_unshift and the entire array was placed under key ‘0’ in the resulting array instead of being placed onto the beginning of the array.
An associative array doesn’t have an order so you don’t need unshift to add key/value pairs, you simply add them to the array without worrying where they end up.
I need the associative array in a certain order because its values are being iterated over and put into a custom-ordered string, and the first part of that string is important for later usage of the data outside of my app. (I don’t have any control over the interpretation of the string itself.) I could add the values I need at the beginning of the string once the string is made, but this requires some regex which I am trying to avoid.
In that case you need an ordered array not an associative array. Each element in your ordered array would be an associative array of one element. That’s the only way to have an ordered array of key/value pairs.
I do not need to order the whole array, just prepend it with certain values. Think of the prepended information as metadata like the type of data in the string. It is more of a faux ordering.
Edit: In case I was unclear, the “ordering” I am talking about is the order the data is the same order that is displayed when you var_dump an array, and not some internal ordering in PHP.
That’order’ is allowed to be any order at all - that it comes out in a particular order every time is a result of the particular compiler used and is not defined by PHP at all - if it came out in a different order it would still be as correct.
I haven’t seen any in-depth documentation about how PHP deals with arrays, but depending on it returning in a set order that isn’t explicit seems like it would be fragile.
Arrays are complex
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
And even if PHP did return the array as one might expect it to, it could get difficult to follow code to know if functions were working with a copy of the array or the actual array itself.
IMHO it would be best to do as felgall suggested and explicitly assign the key value pairs to a numerically keyed multi-dimensional array if only for peace of mind.