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?

3
  • possible duplicate of Insert new item in array on any position in PHP Commented Sep 4, 2014 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 Commented Sep 4, 2014 at 18:19
  • 2
    The linked question has better answer than this @Citizen Commented Sep 4, 2014 at 18:39

4 Answers 4

32

Use array_splice as following:

array_splice($array, 3, 0, array('d'));
Sign up to request clarification or add additional context in comments.

Comments

2

See array_splice

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.