PHP ucfirst() Function
PHP ucfirst() Syntax
ucfirst(string $string): string
PHP ucfirst() Basic examples
echo ucfirst("hello world");
Hello world
Uppercases the first character.
PHP ucfirst() Real-world usage
$name = "john";
echo ucfirst($name);
John
Formats names for display.
PHP ucfirst() Edge cases
echo ucfirst("123abc");
123abc
Non-letter characters are not affected.
PHP ucfirst() Common mistakes
Expecting full title casing
ucfirst only affects the first character.
echo ucfirst("hello world");
echo ucwords("hello world");
Use ucwords() to capitalize each word.
PHP ucfirst() Frequently Asked Questions
What does ucfirst() do in PHP?
ucfirst() converts the first character of a string to uppercase.
Does ucfirst() affect the rest of the string?
No, ucfirst() only changes the first character and leaves the rest unchanged.
Is ucfirst() multibyte-safe?
No, ucfirst() is not multibyte-safe. Use mb_convert_case() for UTF-8 strings.
Does ucfirst() modify the original string?
No, ucfirst() returns a new string and does not modify the original variable unless reassigned.
What happens if the string starts with a non-letter?
ucfirst() will not change the string if the first character is not alphabetic.
What is the difference between ucfirst() and ucwords()?
ucfirst() capitalizes only the first character, while ucwords() capitalizes the first character of each word.
Does ucfirst() work with Unicode characters?
No, ucfirst() may not handle Unicode correctly. Use multibyte-safe alternatives.
Can ucfirst() be used for formatting names?
Yes, ucfirst() can be used to format names, but ucwords() is often more suitable.
What happens if the string is empty?
ucfirst() returns an empty string if the input string is empty.
Is ucfirst() case-sensitive?
ucfirst() only changes the first character to uppercase and does not affect other characters.
Can ucfirst() handle arrays?
No, ucfirst() works only with strings. Use array_map() for arrays.
What is a real-world use case of ucfirst()?
ucfirst() is commonly used to format sentences or ensure proper capitalization of strings.