Insert an item at a specific position in an array in PHP
This post will discuss how to insert an item at a specific position in an array in PHP.
1. Using array_slice() function
A simple solution to insert an item at a specific position in an array is using the array_slice() function. The idea is to extract a slice of the array using array_slice() function and then recombine the parts using the array_merge() function.
The following code demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $arr = [1, 2, 3, 5]; $pos = 3; $val = 4; $result = array_merge(array_slice($arr, 0, $pos), array($val), array_slice($arr, $pos)); print_r($result); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
For associative arrays,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $array = array( 'b' => 'blue', 'r' => 'red', 'g' => 'green' ); $pos = 3; $val = array('y' => 'yellow'); $result = array_merge(array_slice($array, 0, $pos), $val, array_slice($array, $pos)); print_r($result); /* Output: Array ( [b] => blue [r] => red [g] => green [y] => yellow ) */ ?> |
For associative arrays, we can also use the union operator (+) to recombine the parts, which appends the right-hand array to the left-hand array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $array = array( 'b' => 'blue', 'r' => 'red', 'g' => 'green' ); $pos = 1; $val = array('y' => 'yellow'); $result = array_slice($array, 0, $pos) + $val + array_slice($array, $pos); print_r($result); /* Output: Array ( [b] => blue [y] => yellow [r] => red [g] => green ) */ ?> |
Note that for a normal array where the keys are integer, + operator might not work as expected.
2. Using array_splice() function
Another solution is to use array_splice() function, which removes a portion of the array and replace it with the elements of the specified array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $arr = [1, 2, 3, 5]; $pos = 3; $val = 4; array_splice($arr, $pos, 0, $val); print_r($arr); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ ?> |
Note that array_splice() does not preserve numeric keys. Consider the following example, which is trying to splice an associative array with numeric keys using array_splice() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $arr = array( 0 => 'blue', 1 => 'red', 2 => 'green' ); $pos = 1; $val = 'yellow'; array_splice($arr, $pos, 0, $val); print_r($arr); /* Output: Array ( [0] => blue [1] => red [2] => green [3] => yellow ) */ ?> |
That’s all about inserting an item at a specific position in an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)