NikiC NikiC - 11 months ago 80
PHP Question

Change array key without changing order

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

$array[$newKey] = $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.)

Answer Source

Tested and 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" does not exit', $old_key));
    $keys[$index] = $new_key;
    return array_combine($keys, array_values($array));

$new_array = replace_key($array, "b", "e");