August 2nd, 2006

PHP: Insert Into an Array at a Specific Position

It's fairly simple to add an element to an array in PHP, but doing just appends the value/element to the last position in the array. You could hack the array_splice function to attempt the, and the format would be like this: array_splice($array, $pos, 0, $newelement); (you could even insert an entire array into the array!). But this function has been created for the sole purpose of inserting into an array, and it's called array_insert().

function array_insert(&$array, $insert, $position = -1) {
     $position = ($position == -1) ? (count($array)) : $position ;
     if($position != (count($array))) {
          $ta = $array;
          for($i = $position; $i < (count($array)); $i++) {
               if(!isset($array[$i])) {
                    die(print_r($array, 1)."\r\nInvalid array: All keys must be numerical and in sequence.");
               }
               $tmp[$i+1] = $array[$i];
               unset($ta[$i]);
          }
          $ta[$position] = $insert;
          $array = $ta + $tmp;
          //print_r($array);
     } else {
          $array[$position] = $insert;         
     }
         
     ksort($array);
     return true;
}

3 Responses to ' PHP: Insert Into an Array at a Specific Position '

Subscribe to comments with RSS or TrackBack to ' PHP: Insert Into an Array at a Specific Position '.

  1. walid said,

    on February 8th, 2007 at 9:57 pm

    why not
    array_splice($array, $position, 0, $insert);

  2. code cowboy said,

    on February 5th, 2008 at 4:47 am

    Hi,

    Any chance you could comment your function to explain what it is doing internally?

    thanks,

  3. tenzin said,

    on May 19th, 2008 at 6:03 am

    function array_insert(&$array, $insert, $position) {
    array_splice($array,$position,0,$insert);
    }

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image