php - Change array key without changing order -


you can "change" key of array element setting new key , removing old:

$array[$newkey] = $array[$oldkey]; unset($array[$oldkey]); 

but move key end of array.

is there elegant way change key without changing order?

(ps: question out of conceptual interest, not because need anywhere.)

tested , works :)

$array = array( "a" => "1", "b" => "2", "c" => "3" );  function replace_key($array, $old_key, $new_key) {     $keys = array_keys($array);     if (false === $index = array_search($old_key, $keys)) {         throw new exception(sprintf('key "%s" not exit', $old_key));     }     $keys[$index] = $new_key;     return array_combine($keys, array_values($array)); }  $new_array = replace_key($array, "b", "e"); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -