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:
function search_and_insert($input, $afterKey, $newItems) {
$keys = array_keys($input);
$insertPosition = array_search($afterKey, $keys);
if ($insertPosition === false) {
return false;
}
++$insertPosition;
$newKeys = array_keys($newItems);
array_splice($keys, $insertPosition, 0, $newKeys);
array_splice($input, $insertPosition, 0, $newItems);
return array_combine($keys, $input);
}
The idea here is that you process keys and values separately, splicing once for each array, and afterwards use array_combine
to get the end result. Another good idea would be to write a reusable array_splice_assoc
function using the same technique and use that instead of having one to do this specific job only.
Usage:
$myarray = array("a"=>"News", "b"=>"Articles", "c"=>"images");
$newItems = array("j"=>"Latest News", "k"=>"Sports News", "l"=>"Entertainment");
$insertAfter = "a";
print_r(search_and_insert($myarray, "a", $newItems));
See it in action.