In this tutorial I will show you, how to Convert Uppercase to Lowercase, Lowercase to Uppercase without using PHP string functions.
Let’s take a simple example of convert uppercase to lowercase and lowercase to uppercase.
$str = 'tricksofit'; for($i=0; $i<strlen($str); $i++) { echo chr(ord($str[$i])-32); } echo "<hr>"; $str = 'WELCOME'; for($i=0;$i<strlen($str);$i++) { echo chr(ord($str[$i])+32); }
Explanation:
ASCII values of lowercase characters(a-z) are from 97-122 and ASCII values of uppercase characters(A-Z) are from 65-90.
ORD() function returns ASCII value of character.
Difference between ASCII values of lowercase characters to uppercase character is 32.
for ex :
a – 97
A – 65
Difference is – 32.
Like above, all the characters have the difference is 32 only. like b-B -> 98-66 = 32.
So in the above example, I have used “for loop” of a string. It displayed all characters by $str[$i].
ord($str[$i]) returns the ASCII value of the each character. Then I subtracted 32 from this value. Then chr() function returns a specific character based on the ASCII value.
To convert uppercase letters to lowercase letters, follow the same procedure. But, instead of subtracting 32, here we need to add 32 to the ASCII value.