Convert Strings to Uppercase or Lowercase

PHP includes several functions that convert characters in strings to uppercase or lowercase. Pass a string to these functions and they will apply upper or lower case to either:

  • The entire string (strtolower and strtoupper),
  • The first character of the string (lcfirst and ucfirst), or
  • The first character of each word in the string (ucwords).

We demonstrate and describe each of these functions below.

Convert String to Lowercase

The strtolower function returns a string with all characters in lower case. In the example shown here, we pass a string which includes some uppercase characters to strtolower. When we display the result using echo, we can see that the string is now all lowercase characters:

// pass string to strtolower, display result using echo
echo strtolower('Hello World!'); // hello world! 

Convert String to Uppercase

The strtoupper function returns a string with all characters in upper case:

// pass string to strtoupper, display result using echo
echo strtoupper('Hello World!'); // HELLO WORLD!

We pass the same string to strtoupper and see that echo displays the result with all uppercase characters.

Convert First Letter to Uppercase

The ucfirst function returns a string with the first letter in uppercase. We demonstrate here by passing the variable $name, which contains all lowercase characters, to ucfirst. In the result displayed using echo, the name is capitalized:

$name = 'jon'; // all lowercase characters
// pass $name to ucfirst 
echo 'Hello, my name is ' . ucfirst($name);
// Hello, my name is Jon 

Convert First Letter to Lowercase

The lcfirst function returns a string with the first letter in lowercase. We demonstrate here passing 'January' to see it returned as 'january':

echo lcfirst('January'); // january

The lcfirst function is a relative newcomer to PHP, available as of version 5.3.

Uppercase First Letter of Words in String

The ucwords function returns a string with the first letter of each word in uppercase, as we demonstrate here:

// pass a phrase to ucwords
echo ucwords('a title without caps'); 
// A Title Without Caps

We display the results using echo which shows that the ucwords function returns a string with each word capitalized.

Back to top