9

I have an array with 3 values:

$b = array('A','B','C');

This is what the original array looks like:

Array ( [0] => A [1] => B [2] => C )

I would like to insert a specific value(For example, the letter 'X') at the position between the first and second key, and then shift all the values following it down one. So in effect it would become the 2nd value, the 2nd would become the 3rd, and the 3rd would become the 4th.

This is what the array should look like afterward:

Array ( [0] => A [1] => X [2] => B [3] => C )

How do I insert a value in between two keys in an array using php?

1

2 Answers 2

26

array_splice() is your friend:

$arr = array('A','B','C');
array_splice($arr, 1, 0, array('X'));
// $arr is now array('A','X','B','C')

This function manipulates arrays and is usually used to truncate an array. However, if you "tell it" to delete zero items ($length == 0), you can insert one or more items at the specified index.

Note that the value(s) to be inserted have to be passed in an array.

3

There is a way without the use of array_splice. It is simpler, however, more dirty.

Here is your code:

$arr = array('A', 'B', 'C');
$arr['1.5'] = 'X'; // '1.5' should be a string

ksort($arr);

The output:

Array
(
    [0] => A
    [1] => B
    [1.5] => X
    [2] => C
)
2
  • 1
    This doesn't actually answer the question, since it relies on already knowing all the indexes. What if you want to push something between 1 and 2 again? You need to remember if there is 1.5 already or not.
    – Mandemon
    Commented Aug 31, 2017 at 10:50
  • But it is a good quick fix if you just need to enter one value at a specific position. +1
    – Larzan
    Commented Apr 3, 2018 at 16:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.