In PHP, the ucfirst() function is used to convert the first character of a string to uppercase, while leaving the rest of the string unchanged.
Syntax:
ucfirst(string $string): string
Example 1: Basic Usage
<?php
$string = "hello world!";
$capitalized = ucfirst($string);
echo $capitalized; // Output: Hello world!
?>
In this example, the first letter of the string "hello world!" is converted to uppercase, resulting in "Hello world!".
Example 2: String with Multiple Words
<?php
$string = "hello world! welcome to php.";
$capitalized = ucfirst($string);
echo $capitalized; // Output: Hello world! welcome to php.
?>
Notice that ucfirst() only changes the first letter of the string. The subsequent words remain the same.
Example 3: Non-Alphabetic First Character
<?php
$string = "123 apple";
$capitalized = ucfirst($string);
echo $capitalized; // Output: 123 apple
?>
If the string starts with a non-alphabetic character (e.g., a number), ucfirst() does not alter the string.
Example 4: Using ucfirst() on a String with Special Characters
<?php
$string = "#hello world!";
$capitalized = ucfirst($string);
echo $capitalized; // Output: #hello world!
?>
In this case, the # character is preserved, and only the first alphabetic character (h) is capitalized.
This function is handy when you want to make sure that the first letter of a string (such as a name or title) is uppercase, but you don't want to alter the rest of the string.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
