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?

zeckdude
  • 15,877
  • 43
  • 139
  • 187

2 Answers2

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.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
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
)
dodo254
  • 519
  • 2
  • 7
  • 16
  • 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 Aug 31 '17 at 10:50
  • But it is a good quick fix if you just need to enter one value at a specific position. +1 – Larzan Apr 03 '18 at 16:43