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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.