In PHP, how do you change the key of an array element?

后端 未结 23 2760
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  我寻月下人不归
    2020-11-22 04:40

    Here is a helper function to achieve that:

    /**
     * Helper function to rename array keys.
     */
    function _rename_arr_key($oldkey, $newkey, array &$arr) {
        if (array_key_exists($oldkey, $arr)) {
            $arr[$newkey] = $arr[$oldkey];
            unset($arr[$oldkey]);
            return TRUE;
        } else {
            return FALSE;
        }
    }
    

    pretty based on @KernelM answer.

    Usage:

    _rename_arr_key('oldkey', 'newkey', $my_array);
    

    It will return true on successful rename, otherwise false.

提交回复
热议问题