PHP Program to convert the uppercase letters to lowercase and lowercase letters to uppercase

How to convert the uppercase letters to lowercase and lowercase letters to uppercase using PHP?

In this program to convert the case of the letters we are using the built-in functions strtoupper() and strtolower(). And for that we first check every letter of the string using the built-in function ctype_lower() and ctype_upper(). If the letter is lower we convert it to upper and if it is upper we convert it to lower. For example, if the entered string id Hi Welcome to LearnETutorials.com then the output will be hI wELCOME TO lEARNetUTORIALS.COM.

Syntax


strtolower(string);
strtoupper(string);
ctype_lower(string);
ctype_upper(string);
 

 

ALGORITHM

Step 1: Read the string from the user and assign it to the variable string

Step 2: Assign the length of the variable string into the variable len

Step 3: Assign the value 0 into the variable i and perform the following sub-steps until the condition 'i < len' becomes false and increment the value of the variable i in every iteration

        (i) Check the condition 'ctype_lower(string[i])' if it is true then assign the value of 'strtoupper(string[i])' into the variable string[i] otherwise assign                  the value of 'strtolower(string[i])' into the variable string[i]

Step 4: Print the value of the variable string as the converted value of the entered string

PHP Source Code

                                          <?php

$string = readline("Enter the string: ");
$str  = $string;
$len = strlen($string);
for ($i = 0; $i < $len; $i++) {
    if (ctype_lower($string[$i])) {
        $string[$i] = strtoupper($string[$i]);
    } else {
        $string[$i] = strtolower($string[$i]);
    }
}
echo "Case Converted string of $str is: $string";
?>
                                      

OUTPUT

Case Converted string of Hello All Welcome To LearnETutorials.COM is: hELLO aLL wELCOME tO lEARNetUTORIALS.com