i have an associative array in PHP.
$myarray = array(
"a"=>"News",
"b"=>"Articles",
"c"=>"images"
);
I want to insert some values after “a” key. so that the structure of array becomes
$myarray = array(
"a"=>"News",
"j"=>"Latest News",
"k"=>"Sports News",
"l"=>"Entertainment",
"b"=>"Articles",
"c"=>"images"
);
How can i get this functionality.
The function for this is
array_splice, but you are going to have to do some work manually because it does not preserve keys. Let’s make it do that:The idea here is that you process keys and values separately, splicing once for each array, and afterwards use
array_combineto get the end result. Another good idea would be to write a reusablearray_splice_assocfunction using the same technique and use that instead of having one to do this specific job only.Usage:
See it in action.