Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to convert a string to uppercase in PHP?

Answer: Using strtoupper() function

We can convert the string to uppercase using the predefined strtoupper() function. This function takes a string and returns a new string with all the alphabetic characters converted to uppercase.

The strtoupper() function does not change the string. It only converts the alphabetic characters to uppercase.

Example: Using strtoupper() function

In the given example, we have converted all the alphabetic characters of the given string to uppercase using predefined strtoupper() function.

<!DOCTYPE html>
<html>
<head>
  <title>Convert a string to uppercase</title>
</head>
<body>
	<?php
		$str = 'Hello! welcome to studytonight';
		$new_str = strtoupper($str);
		echo $new_str;
	?>
</body>
</html>

Output


HELLO! WELCOME TO STUDYTONIGHT

Without using any built-in function

In the above example, we have used the predefined function to convert all the alphabetic characters of the given string to uppercase. We can also convert the given string to uppercase without using any predefined function. We have created a function that will convert the characters of the string to uppercase.

Example: Without using predefined function

In the given example, we have created a function upperCase that will convert all the alphabetic characters of the string into the uppercase.

<!DOCTYPE html>
<html>
<head>
  <title>Convert a string to uppercase</title>
</head>
<body>
	<?php
		function upperCase($str)
		{
		    $char  = str_split($str);
		    $result = '';
		    
		    for ($i = 0; $i < count($char); $i++) {
		        $ch = ord($char[$i]);
		        
		        if ($char[$i] >= 'a' && $char[$i] <= 'z'){
		            $result .= chr($ch - 32);
		        }
		        
		        else{
		            $result .= $char[$i];
		        }
		        
		    }
		    return $result;
		}
		$string = "hello! welcome to studytonight";
		echo upperCase($string);
	?>
</body>
</html>

Output


HELLO! WELCOME TO STUDYTONIGHT

Conclusion

In this lesson, we have learned how to convert a given string to uppercase. Here, we have discussed two approaches to convert the string to uppercase. At first, we have used the PHP predefined function strtoupper(). This function takes a string and returns a new string with all the uppercase characters. We have created a function without using the library function. The user-defined function converts all the characters of the string to uppercase.



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.