How can I add an element to the beginning of array without changing array key values in PHP?
views:
56answers:
5
                +1 
                A: 
                
                
              Use array_unshift(). (As mentioned, it will keep your string keys intact, but not numeric keys).
                  aularon
                   2010-09-07 09:12:11
                
              "All numerical array keys will be modified to start counting from zero while literal keys won't be touched." (http://www.php.net/array-unshift)
                  Dominic Rodger
                   2010-09-07 09:12:59
                
                +1 
                A: 
                
                
              
            try this:
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;
    }
                  frabiacca
                   2010-09-07 09:12:52
                
              
                +4 
                A: 
                
                
              
            If you use literal keys, array_unshift() will do it.
If you use numeric keys, how should that work? Use '-1' as the new first key?
                  Martin
                   2010-09-07 09:13:26