Uppercase first character of a String in PHP
If you need to uppercase the first character of a string in PHP, you can use the ucfirst() function. This function takes a string as an argument and returns a new string with the first character uppercased.
<?php
echo ucfirst("we are programmers");
// -> We are programmers
?>
To convert the first character of the string to uppercase:
- Get the string that you want to convert the first letter to upercase.
- Pass the string to ucfirst() function and it will return the string with first letter uppercase.
Syntax
ucfirst($str)
# Method 2: Using strtoupper() function
If you do not want to use the ucfirst() function then you can also use strtoupper() function. It converts all the characters of the string to uppercase.
We will get the first character of the string and convert it to uppercase. Then replace it with the first character of the string. Check the below example:
<?php
$str = "hello world";
$str[0] = strtoupper($str[0]);
echo $str;
?>
Output
Hello world
In the above code example, we have a string called $str.
We are getting the first letter from the string using $str[0] and then passing it to strtoupper() function that will return the uppercase format of this letter.
Then replace it with the first letter of the string and print it.
- Uppercase first character of each word of a String in PHP
- Lowercase first character of a String in PHP
- Convert string to uppercase in PHP
- Select first n words of a sentence in PHP
- Get first n words from a paragraph in PHP
- Check empty string in PHP
- Calculate length of a string using strlen() function in php