Do you ever come across a need where you need to insert a value or an array after a specific key in a PHP array?
If yes, did you solve it by yourself?
Ok. If you don’t know the solution yet, here’s the PHP function you can simply use.
function array_insert_after( array $array, $key, array $new ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys );
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}Above function requires 3 parameters
- $array – An array in which you want to insert some values
- $key – A key (string) After which you want to insert values
- $new – $new is an array with value or key/ value pair
Here’s how you can use this code to insert key/ value pair
$numbers = array('one' => 1, 'two' => 2, 'four' => 4);
$three = array('three' => 3);
$numbers = array_insert_after($numbers, 'two', $three);Output of the above code is
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)And if you want to add only value
$numbers = array('one' => 1, 'two' => 2, 'four' => 4);
$three = array(3);
$numbers = array_insert_after($numbers, 'two', $three);Output of the above code is
Array
(
[one] => 1
[two] => 2
[0] => 3
[four] => 4
)I hope this PHP function will be helpful.