PHP Echo Tutorials

Case Functions

Written by phpecho.com   

How would you convert a string into upper case letters? Or how would you convert only the first character into upper case? We will look at these and other string manipulation functions in this tutorial. In particular we will concentrate on case functions.

We will consider four functions - strtolower(), strtoupper(), ucfirst() and ucwords().

The strtolower() function is used to convert all the characters in a string into lower case. So, if your input string is, say, "Hello World", then after being processed by the strtolower() function, the output would be "hello world". Note that it does not matter what the input is. It could be all upper case or a mix of upper case and lower case. Consider this example:

<?php
   $string = "wHat IS the color Of an ORAnge?";
   echo (strtolower($string).'<br>');
   ?>

The output of the above program is:

what is the color of an orange?

The strtoupper() function behaves exactly like the strtolower() function except that it converts all characters into their upper case. Let us use this function in the same example above to note the difference:

<?php
   $string = "wHat IS the color Of an ORAnge?";
   echo (strtolower($string).'<br>');
   echo (strtoupper($string).'<br>');
   ?>

The output is now -

what is the color of an orange?
WHAT IS THE COLOR OF AN ORANGE?

Note the second line of output: all the characters are in block letters.

The next function we will study is ucfirst(). This function will capitalize the first letter of a string. So, if the input string is "hello world", then this function will convert it to "Hello world". Consider the following snippet of code -

<?php
   $string = "what is the color of an orange?";
   echo (ucfirst($string).'<br>');
   ?>

This code gives the output -

What is the color of an orange?

Only the first letter of the string (in this case the sentence) is converted into capital letter.

The final function we will study is ucwords() which converts the first letter of each word into upper case.
So, executing this piece of code -

<?php
   $string = "what is the color of an orange?";
   echo (ucwords($string).'<br>');
   ?>

gives the output

What Is The Color Of An Orange?

The main purpose of these functions will be when you either want to make user input case insensitive or you want to format output in a particular way.