PHP Add Key & Value to Beginning of an Array…

So it turns out there is no built in function to add a key and value to the start of an array. There is;

 

array_unshift() – Prepend one or more elements to the beginning of an array.

 

However, this will only add a value. So the method we use is to create a new array with the key and value you wish to add to another and use;

 

array_combine — Creates an array by using one array for keys and another for its values.

 

For example:

$existingArray = array("fred" => "orange", "john" => "IsaSpy");
$array['our_key'] = "our_value";

$newArray = array_combine($existingArray, $array);

print_r($newArray);

//boom
PHP Add Key & Value to Beginning of an Array…

Leave a Reply

Your email address will not be published. Required fields are marked *