Signup/Sign In

How to convert the first letter of a string to uppercase in PHP?

Answer: Using ucfirst() function

We can convert the first character of a string to uppercase by using the ucfirst() function. It is a built-in PHP function that takes a string as its argument and returns a new string having the first character of the word in uppercase.

This function converts only the first character of the string to uppercase, and other characters remain unchanged.

Example: Convert using ucfirst() function

In the given example, we have converted the first letter of the given string $str to the uppercase using the ucfirst() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Convert the first letter of a string to uppercase</title>
</head> 
<body>  
	<?php
		$str = 'welcome to the studytonight';
		$new_str = ucfirst($str);
		echo $new_str;
	?>
</body>  
</html>  


Welcome to the studytonight

PHP ucwords() function

In the above example, we have used the ucfirst() function to convert the first letter of the string to uppercase. What if we want to convert the first letter of every within the string to uppercase. To do so, we can use another built-in PHP function that is ucwords().

This function takes a string as input and returns a new string having all the first letters of each word within the given string in uppercase.

Example: Convert using ucwords() function

In the given example, we have converted the first letter of each word to uppercase of the given string $str using the ucwords() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Convert the first letter of a string to uppercase</title>
</head> 
<body>  
	<?php
		$str = 'welcome to the studytonight';
		$new_str = ucwords($str);
		echo $new_str;
	?>
</body>  
</html>  


Welcome To The Studytonight

Conclusion

In this lesson, we have learned how to convert the first character of the given string to uppercase.

We first converted only the first character of the string to uppercase using the ucfirst() function, and the remaining characters of the string remain the same then we have converted the first character of each word within the string to uppercase using the ucwords() function.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.