How to Change All Keys of a PHP Array to Uppercase?

You can simply use the array_change_key_case() function in PHP to change the case of all keys in an array. To use this function to change all keys to uppercase, you can specify CASE_UPPER constant as the second argument to the function, for example, like so:

array_change_key_case($array, CASE_UPPER);

If you array contains numeric keys as well, then they're left as is.

For example:

$arr = [
    'Foo' => 1,
    'BAR' => 2,
    'baz' => 3,
    'QuX' => 4,
];

$arrUppercaseKeys = array_change_key_case($arr, CASE_UPPER);

var_dump($arrUppercaseKeys); // ['FOO' => 1, 'BAR' => 2, 'BAZ' => 3, 'QUX' => 4]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.