How to Convert an Array of Strings to Uppercase in PHP?

In PHP, you can make all strings in an array of strings uppercase by calling the strtoupper() function on every element of the array using array_map(), for example, like so:

// PHP 7.4+
$arr = ['foo', 'Bar', 'bAz'];
$newArr = array_map(fn ($str) => strtoupper($str), $arr);

var_dump($newArr); // ['FOO', 'BAR', 'BAZ']

You can rewrite the callback to array_map() without arrow function to make it compatible with earlier versions of PHP.

The code above would create a new array with all strings in the array in uppercase. You can achieve the same with a simple for loop as well:

$arr = ['foo', 'Bar', 'bAz'];
$newArr = [];

foreach ($arr as $str) {
    $newArr[] = strtoupper($str);
}

var_dump($newArr); // ['FOO', 'BAR', 'BAZ']

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.