Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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?

like image 275
zeckdude Avatar asked Nov 20 '11 09:11

zeckdude


2 Answers

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.

like image 161
Linus Kleen Avatar answered Sep 23 '22 23:09

Linus Kleen


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
)
like image 36
dodo254 Avatar answered Sep 19 '22 23:09

dodo254