tags:

views:

56

answers:

5

How can I add an element to the beginning of array without changing array key values in PHP?

+1  A: 

Use array_unshift(). (As mentioned, it will keep your string keys intact, but not numeric keys).

aularon
"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
A: 

array_unshift will not modify non numeric keys

AlberT
+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
+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
A: 

Use array_unshift(); this will help u in adding element

Tejas1810