Tag Archive for code

php: Insert element at specific Index of Array.

In a recent project I’ve been undertaking I’ve made a menu class set and sometimes i just wanted to say to add this to an array, but in a certain position. PHP does this easily via

$array[position] = "newdata";

But unfortunately this is not so good if you only wanted to insert the newdata into that position and move the others the out of the way. So with a little help from Derick Rethans and Tetraboy I came up with this little solution.

Any comments gratefully recieved.

function array_insert(&$array,$element,$position=null) {
  if (count($array) == 0) {
    $array[] = $element;
  }
  elseif (is_numeric($position) && $position < 0) {
    if((count($array)+position) < 0) {
      $array = array_insert($array,$element,0);
    }
    else {
      $array[count($array)+$position] = $element;
    }
  }
  elseif (is_numeric($position) && isset($array[$position])) {
    $part1 = array_slice($array,0,$position,true);
    $part2 = array_slice($array,$position,null,true);
    $array = array_merge($part1,array($position=>$element),$part2);
    foreach($array as $key=>$item) {
      if (is_null($item)) {
        unset($array[$key]);
      }
    }
  }
  elseif (is_null($position)) {
    $array[] = $element;
  }
  elseif (!isset($array[$position])) {
    $array[$position] = $element;
  }
  $array = array_merge($array);
  return $array;
}

and no code would be without it’s example:

// create the array
$x = array("apples","bananas","pears");
//insert "oranges" at position 1
array_insert($x,"oranges",1);
var_dump($x);
//insert "pineapples" 2 from the end
array_insert($x,"pineapples",-2);
var_dump($x);
//insert "strawberries" at the end
array_insert($x,"strawberries");
var_dump($x);
//insert "plums" at position 0 - (because the negative position goes beyond 0)
array_insert($x,"pineapples",-10);
var_dump($x);

or alternatively

// create the array
$x = array("apples","bananas","pears");
//insert "oranges" at position 1
$x = array_insert($x,"oranges",1);
var_dump($x);
//insert "pineapples" 2 from the end
$x = array_insert($x,"pineapples",-2);
var_dump($x);
//insert "strawberries" at the end
$x = array_insert($x,"strawberries");
var_dump($x);
//insert "plums" at position 0 - (because the negative position goes beyond 0)
$x = array_insert($x,"plums",-10);
var_dump($x);