Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change array key without changing order

Tags:

You can "change" the key of an array element simply by setting the new key and removing the old:

$array[$newKey] = $array[$oldKey]; unset($array[$oldKey]); 

But this will move the key to the end of the array.

Is there some elegant way to change the key without changing the order?

(PS: This question is just out of conceptual interest, not because I need it anywhere.)

like image 223
NikiC Avatar asked Jan 16 '12 17:01

NikiC


People also ask

How do you sort array keys?

The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

What is the use of array flip function?

The array_flip() function is used to exchange the keys with their associated values in an array. The function returns an array in flip order, i.e. keys from array become values and values from array become keys. Note: The values of the array need to be valid keys, i.e. they need to be either integer or string.


2 Answers

Tested and works :)

function replace_key($array, $old_key, $new_key) {     $keys = array_keys($array);     if (false === $index = array_search($old_key, $keys, true)) {         throw new Exception(sprintf('Key "%s" does not exist', $old_key));     }     $keys[$index] = $new_key;     return array_combine($keys, array_values($array)); }  $array = [ 'a' => '1', 'b' => '2', 'c' => '3' ];     $new_array = replace_key($array, 'b', 'e'); 
like image 86
Kristian Avatar answered Sep 19 '22 07:09

Kristian


Something like this may also work:

$langs = array("EN" => "English",          "ZH" => "Chinese",          "DA" => "Danish",         "NL" => "Dutch",          "FI" => "Finnish",          "FR" => "French",         "DE" => "German"); $json = str_replace('"EN":', '"en":', json_encode($langs)); print_r(json_decode($json, true)); 

OUTPUT:

Array (     [en] => English     [ZH] => Chinese     [DA] => Danish     [NL] => Dutch     [FI] => Finnish     [FR] => French     [DE] => German ) 
like image 29
anubhava Avatar answered Sep 18 '22 07:09

anubhava