PHP How to Convert String to Uppercase Easily
Use the built-in PHP function
strtoupper() to convert any string to uppercase, like strtoupper('hello') which returns 'HELLO'.Examples
Inputhello
OutputHELLO
InputPhp is fun!
OutputPHP IS FUN!
Input123abc!@#
Output123ABC!@#
How to Think About It
To convert a string to uppercase in PHP, think of changing every letter to its capital form. PHP provides a simple function that takes your string and returns a new string with all letters in uppercase, leaving numbers and symbols unchanged.
Algorithm
1
Get the input string.2
Pass the string to the uppercase conversion function.3
Receive the converted uppercase string.4
Return or print the uppercase string.Code
php
<?php
$input = "hello world!";
$output = strtoupper($input);
echo $output;
?>Output
HELLO WORLD!
Dry Run
Let's trace converting 'hello' to uppercase using strtoupper()
1
Input string
The input string is 'hello'
2
Call strtoupper()
strtoupper('hello') processes each character
3
Output string
Returns 'HELLO'
| Original | Uppercase |
|---|---|
| hello | HELLO |
Why This Works
Step 1: Function Purpose
The strtoupper() function converts all alphabetic characters in the string to uppercase.
Step 2: Non-alphabetic Characters
Characters like numbers and symbols remain unchanged because they have no uppercase form.
Step 3: Return Value
The function returns a new string with uppercase letters, leaving the original string unchanged.
Alternative Approaches
mb_strtoupper() for multibyte strings
php
<?php $input = "héllo wörld!"; $output = mb_strtoupper($input, 'UTF-8'); echo $output; ?>
Use this when working with UTF-8 strings containing accented or special characters to correctly convert them.
Manual loop with strtoupper() on each character
php
<?php $input = "hello"; $output = ''; for ($i = 0; $i < strlen($input); $i++) { $output .= strtoupper($input[$i]); } echo $output; ?>
This is less efficient and more complex but shows how uppercase conversion works character by character.
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each character once, so time grows linearly with string length.
Space Complexity
A new string is created for the uppercase result, so space also grows linearly with input size.
Which Approach is Fastest?
strtoupper() is fastest for ASCII strings; mb_strtoupper() is needed for UTF-8 but slightly slower due to encoding handling.
| Approach | Time | Space | Best For |
|---|---|---|---|
| strtoupper() | O(n) | O(n) | Simple ASCII strings |
| mb_strtoupper() | O(n) | O(n) | UTF-8 strings with accents |
| Manual loop with strtoupper() | O(n) | O(n) | Educational purposes, not recommended |
Use
strtoupper() for simple ASCII strings and mb_strtoupper() for UTF-8 encoded strings with special characters.Forgetting to use
mb_strtoupper() when working with UTF-8 strings, which can cause incorrect uppercase conversion.