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?

HamZa
  • 14,671
  • 11
  • 54
  • 75
khernik
  • 167
  • 1
  • 8

2 Answers2

5
$array = array_slice($array, 0, $index) 
       + array($newElement)
       + array_slice($array, $index, count($array) - 1);
nice ass
  • 16,471
  • 7
  • 50
  • 89
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.

ryanbwork
  • 2,123
  • 12
  • 12