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.
Important Note:It won't work if the keys are not in the array.
My solution is (I love using native php array functions);
It is pretty simple and you can turn it into a function easily.
Here's another way:
There is a super simple way to do this that I came up with tonight.It will search for a key, splice it like normal and return the removed element like the normal function.
This works like
array_splice
, but preserves the keys of the inserted array:You use this as you would
array_splice
, but just add ak
at the end. (ragulka's answer is good, but this makes it easier to adapt existing code.) So, for exampleInstead of
use
Then
$a
will contain the result you're looking for.I think you need to do that manually:
My solution mimics array_splice exactly, the second parameter is now
String $key,
instead ofInt $offset,
So to get the result you require you would do
Output