array_insert for PHP

published on March 24, 2014 in Tips and Tricksno comments

Similar to array_splice, this array_insert function allows to insert an object in an array – thing that unfortunately is not possible with array_splice that deals only with array parameters. This function offers an option for replacing the item correspondent to the offset.

function array_insert($array, $offset, $object[, $replace=false])

$array is the array to be modified
$offset is the position where we want to insert our object. It needs to be positive and within the limits given by the dimension of the array. If it is less than 0, the object will be inserted as the first element; if it is over the maximum dimension, the object will be inserted as the final element.
$object is the object to be inserted.
$replace is an optional parameter that indicates if the array element is going to be replaced. Default is false.

Follows the code.

The array_insert name is currently unused in PHP, but I would suggest to change the name in your code (something like sd_array_insert) or the namespace, just in case PHP developer will introduce a function with this name.

function array_insert(&$array, $offset, $object, $replace=false){
    
    if(is_array($array)){
        if($replace ){
            if($offset<0) $offset = 0;
            else if($offset > count($array)-1) $offset = count($array)-1;
            $a1 = array_slice($array, 0, $offset);
            $a2 = array_slice($array, $offset+1);
            array_push($a1, $object);
            $array = array_merge($a1, $a2);
        }else{            
            if($offset == 0){
                array_unshift($array, $object);
            }else if($offset >= count($array)){
                array_push($array, $object);
            }else{                
                $a1 = array_slice($array, 0, $offset);
                $a2 = array_slice($array, $offset);
                array_push($a1, $object);
                $array = array_merge($a1, $a2);
            }
        }
    }    
}

if your PHP version is (PHP 5 >= 5.3.0), then you can also use the following version.

function array_insert(&$array, $offset, $object, $replace=false){
    
    if(is_array($array)){
        if($replace ){
            if($offset<0) $offset = 0;
            else if($offset > count($array)-1) $offset = count($array)-1;
            $array = array_replace($array, array($offset => $object));
        }else{            
            if($offset == 0){
                array_unshift($array, $object);
            }else if($offset >= count($array)){
                array_push($array, $object);
            }else{                
                $a1 = array_slice($array, 0, $offset);
                $a2 = array_slice($array, $offset);
                array_push($a1, $object);
                $array = array_merge($a1, $a2);
            }
        }
    }    
}
Tags:

Leave a reply