Change array key without changing order
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
)
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');