0
0
PhpHow-ToBeginner · 3 min read

How to Use ucfirst in PHP: Capitalize First Letter Easily

In PHP, use the ucfirst function to capitalize the first character of a string. It takes a string as input and returns the string with its first letter converted to uppercase.
📐

Syntax

The ucfirst function has a simple syntax:

  • ucfirst(string $string): string

Here, $string is the input text. The function returns the same string but with the first character changed to uppercase if it is a letter.

php
<?php
string ucfirst(string $string)
?>
💻

Example

This example shows how to use ucfirst to capitalize the first letter of a word.

php
<?php
$word = "hello world!";
$capitalized = ucfirst($word);
echo $capitalized;
?>
Output
Hello world!
⚠️

Common Pitfalls

One common mistake is expecting ucfirst to capitalize every word in a sentence. It only changes the first character of the entire string.

Also, ucfirst does not change the rest of the string, so if the first letter is already uppercase, the string stays the same.

php
<?php
// Wrong: expecting all words capitalized
$sentence = "hello world!";
echo ucfirst($sentence); // Outputs: Hello world!

// Right: use ucwords for all words
echo ucwords($sentence); // Outputs: Hello World!
?>
Output
Hello world! Hello World!
📊

Quick Reference

ucfirst capitalizes only the first character of a string.

Use ucwords to capitalize the first letter of each word.

Input must be a string; non-string inputs will be converted to string.

FunctionDescription
ucfirst(string $string)Capitalizes the first character of the string.
ucwords(string $string)Capitalizes the first character of each word in the string.

Key Takeaways

Use ucfirst to capitalize only the first letter of a string in PHP.
ucfirst does not affect letters beyond the first character.
To capitalize the first letter of each word, use ucwords instead.
ucfirst returns the modified string; it does not change the original variable unless reassigned.
Input to ucfirst should be a string; other types are converted automatically.