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.)
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.
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.
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');
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With