22

Lets say I have this array:

$array = array(1,2,'b','c',5,6,7,8,9.10);

Later in the script, I want to add the value 'd' before 'c'. How can I do this?

Citizen
  • 12,430
  • 26
  • 76
  • 117
  • possible duplicate of [Insert new item in array on any position in PHP](http://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php) – Michel Ayres Sep 04 '14 at 17:18
  • 1
    @MichelAyres The question that you linked to was posted after this one. I think that makes his a duplicate of mine, not the other way around :P – Citizen Sep 04 '14 at 18:19
  • 2
    The linked question has better answer than this @Citizen – Michel Ayres Sep 04 '14 at 18:39

4 Answers4

32

Use array_splice as following:

array_splice($array, 3, 0, array('d'));
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
2

See array_splice

mob
  • 117,087
  • 18
  • 149
  • 283
0

or a more self-made approach: Loop array until you see 'd' insert 'c' then 'd' in the next one. Shift all other entries right by one

Vladimir
  • 417
  • 5
  • 20
0

The Complex answer on Citizen's question is:

$array = array('Hello', 'world!', 'How', 'are', 'You', 'Buddy?');
$element = '-- inserted --';
if (count($array) == 1)
{
    return $string;
}
$middle = ceil(count($array) / 2);
array_splice($array, $middle, 0, $element);

Will output:

Array
(
    [0] => Hello
    [1] => world!
    [2] => How
    [3] => -- inserted --
    [4] => are
    [5] => You
    [6] => Buddy?
)

So thats what he want.

Petr Hladík
  • 527
  • 6
  • 8