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;
}
  • Share/Bookmark

14 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);
    }


  4. on June 10th, 2008 at 3:50 am

    Could you explain the difference between your code and:

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

  5. celebhir said,

    on June 18th, 2008 at 4:43 am

    you rock tenzin – little pieces of clever code, my favourte.
    thanks. works like a dream

  6. leafo said,

    on July 14th, 2008 at 10:10 am

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

    wrap what you are inserting in the call to array splice in an array that way you can insert complex objects (like arrays). Otherwise the splice method will iterate though the object and individually insert each thing in it.

  7. vladimir said,

    on July 16th, 2008 at 7:58 am

    some offtopic comment:
    it's hard to find this page among firefox tabs because desing of favicon is not visually associated with page's design. make a dark favicon.
    sorry my english (:

  8. stephen said,

    on January 14th, 2009 at 4:11 pm

    from http://us2.php.net/array_slice:

    Note: If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .


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

    fixes things for me.

  9. Kovu said,

    on April 3rd, 2009 at 1:23 pm

    I've written the following code for inserting array elements:

    function array_insert(&$array, $insert, $position){
    if(!is_numeric($position)) return false;
    if($position = $length){
    $array = array_merge($array, array($insert));
    }else{
    $head = array_slice($array, 0, $position);
    $insert = array($insert);
    $tail = array_slice($array, $position);
    $array = array_merge($head, $insert, $tail);
    }

    return true;
    }

    It's a different approach to solve this problem, with array_slice() and array_merge(). I find that solution to be more trustworthy and use that to handle complex multidimensional arrays.

  10. Kovu said,

    on April 3rd, 2009 at 1:30 pm

    My code above didn't parse correctly… due to what reason ever… you want the working code, visit my community: http://terrasco.hostingdelivered.com/

  11. Ed said,

    on April 4th, 2009 at 12:32 pm

    If you're inserting arrays into arrays…

    line #2 should be:

    if (is_object($insert) OR is_array($insert) {

  12. PhpMyCoder said,

    on September 2nd, 2009 at 8:51 am

    As many have said now, using array_splice() is very unreliable. If you store any complex objects in the array the array_splice() function will iterate through all the elements of the array and all of the elements for each of the objects in the array. This causes serious problems as it may insert something in the middle of a class (I just spent several days now trying to figure out why my classes were throwing errors). The array_insert() function is definitely what I would use. In fact, it would be a convenient function to have packaged with PHP.

  13. PhpMyCoder said,

    on September 2nd, 2009 at 8:56 am

    @stephen:
    That seemed to fix my problem…very ingenious solution. I still wouldn't reply on the array_splice() function, but as long as I see no errors with this, it's a great fix!

  14. malte said,

    on October 14th, 2009 at 12:57 pm

    Quote from PHP.net / splice function manual:

    "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself."

    I do not know since when this is in PHP, but if you've got a recent PHP version, there is no need for array($object) any longer to use as replacement. try it on your own.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word