Change array key without changing order

arrays, php

Solution

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');

Problem

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.)

Original source

Related problems