3

I want to insert new element after specific index of non-asociative array in PHP. This is what I've done as far:

public function insertAfter($newElement, $key)
{
    // Get index of given element
    $index = array_search($key, array_keys($array));

    $temp  = array_slice($array, $index + 1, null, TRUE);
    $temp2 = array_slice($array, sizeof($array) - $index, null, TRUE);

    // Insert new element into the array
    $array = array_merge($temp, array($newElement), $temp2);
}

However, it doesn't really do what I want...it does some strange things with the array. Could you help?

4
  • 2
    stackoverflow.com/questions/3797239/… Commented Feb 26, 2013 at 21:46
  • 1
    Pass $array as a function argument. Otherwise you're slicing nothing. insertAfter($newElement, $key, $array) Commented Feb 26, 2013 at 21:47
  • 1
    $array is attribute, $this->array, sorry I didn't write this, it IS the array with some content Commented Feb 26, 2013 at 21:48
  • 1
    can you post the result of print_r($array) ? Commented Feb 26, 2013 at 21:49

2 Answers 2

5
$array = array_slice($array, 0, $index) 
       + array($newElement)
       + array_slice($array, $index, count($array) - 1);
Sign up to request clarification or add additional context in comments.

Comments

1

The second argument to array_slice should be the offset in the array where the sub array will start. If you're trying to split the array into two, you'd want the first sub array to start at offset 0 and be of size $index, and the second sub array to start at offset $index+1 and be of size sizeof(array) - index. To reiterate a comment though, array_splice is better suited for your application.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.