How to Capitalize First Letter in an Array of Strings in PHP?

In PHP, you can capitalize the first letter of every string in an array of strings by calling the ucfirst() function on every element of the array using array_map(), for example, like so:

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

var_dump($newArr); // ['Foo Bar', 'Baz', 'Qux']

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 having the first letter capitalized (and the remaining string unchanged). You can achieve the same with a simple for loop as well:

$arr = ['foo Bar', 'baz', 'qux'];
$newArr = [];

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

var_dump($newArr); // ['Foo Bar', 'Baz', 'Qux']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.