Say I have an associative array:
array(
"color" => "red",
"taste" => "sweet",
"season" => "summer"
);
and I want to introduce a new element into it:
"texture" => "bumpy"
behind the 2nd item but preserving all the array keys:
array(
"color" => "red",
"taste" => "sweet",
"texture" => "bumpy",
"season" => "summer"
);
is there a function to do that? array_splice()
won't cut it, it can work with numeric keys only.
I'm not sure if there is a function for that, but you can iterate through your array, store the index and use array_push.
I hate to beat an old issue to death, it seems like some people have come up with some similar answers to mine already. But I'd like to offer a version that I think is just a little more thorough. This function is designed to feel and behave -exactly- like the regular array_splice() one, including its return value and how it handles invalid or negative values. The only difference in that regard is that when defining a replacement array (or string or number) and not a length, you're allowed to use a null value for the length instead of having to pass count($array) as an argument. It will assume that much from a null. 0 is still 0 though.
The only difference in function is of course the $key value parameter, specifying what key to derive a position from to start making changes. The $offset has been left in as well, now used as a modifier for that initial position. Key conflicts will always favor the replacement array but also trigger a warning. And if the key parameter is null or blank, the function will look only to the offset parameter and behave like array_splice, except while maintaining key values. If the key is simply not found though, it will behave the same way array_splice does when given an offset that's beyond the array length; it appends it to the end.
So then...
This could also be a simpler way to replace individual array keys while maintaining its position, without having to go through array_values and array_combine.
EDIT: I just discovered, apparently array_merge() can't really tell the difference between associative array keys that just happen to be numbers, and regular sequential keys. Merging the arrays using the + operator instead of array_merge() avoids this problem.
Well, you can rebuild the array from scratch. But the easiest way to go through an associative array in a particular order is to keep a separate ordering array. Like so:
Based on solution provided by ragulka and soulmerge, I created a
slightly different function
that let's you specify the 'key' instead of offset.Based on soulmerge's answer I created this handy function: