Change array key without changing order

前端 未结 8 1577
难免孤独
难免孤独 2020-12-03 07:17

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


        
8条回答
  •  無奈伤痛
    2020-12-03 07:48

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

提交回复
热议问题