Summary: in this tutorial, you’ll learn how to use the PHP ucfirst()
function to make the first alphabetic character uppercase.
Introduction to the PHP ucfirst() function
The ucfirst()
function accepts a string and returns a new string with the first character converted to uppercase if that character is alphabetic.
Here’s the syntax of the ucfirst()
function:
ucfirst ( string $string ) : string
Code language: PHP (php)
The ucfirst()
function use the current locale to determine which character is alphabetic.
PHP ucfirst() function example
The following example uses the ucfirst()
function to convert the first characters of the first name and last name to uppercase:
<?php
$first_name = 'john';
$last_name = 'doe'
echo ucfirst($first_name) . ' ' . ucfirst($last_name);
Code language: PHP (php)
Output:
John Doe
Code language: PHP (php)
Dealing with multibyte characters
The ucfirst()
doesn’t support multibyte strings. To return a new string with the first character converted to uppercase, you can use the following mb_ucfirst()
function:
<?php
function mb_ucfirst($str)
{
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
Code language: PHP (php)
How it works.
First, get the first character of the $str
using the mb_substr()
function and convert it to uppercase using the mb_strtoupper() function:
mb_strtoupper(mb_substr($str, 0, 1))
Code language: PHP (php)
Then, concatenate the uppercase character with the remaining characters in the string:
mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
Code language: PHP (php)
The following example uses the ucfirst()
to convert the first letter of the string äbtissin
to uppercase:
<?php
$title = 'äbtissin';
echo ucfirst($title); // doesn't work
Code language: PHP (php)
Output:
äbtissin
Code language: PHP (php)
However, it doesn’t work as expected. Because in the default “C” locale characters, the ucfirst()
function doesn’t convert character like umlaut-a (ä
).
The following uses the mb_ucfirst()
function instead:
<?php
$title = 'äbtissin';
echo mb_ucfirst($title);
Code language: PHP (php)
Output:
Äbtissin
Code language: PHP (php)
Now, it works as expected.
Summary
- Use the
ucfirst()
function to returns a string with the first alphabetic character converted to uppercase.