- Get the string input on which the case should be toggled
- Calculate the length of the string
- Iterate to get the ASCII code of each string
- Check whether the ASCII code is range between [64-91] which is upper case
- Check whether the ASCII code is range between [96-123] which is lower case
- If its upper case add 32 to make it lower case
- If its lower case subtract 32 to make it upper case
- Check the condition only for alphabets
- Finally concatenate the string
<?php $string = "MyDons - Helps Make Better"; // the string which need to be toggled case $string_length = strlen($string); // calculate the string length for($i=0;$i<$string_length;$i++){ // iterate to find ascii for each character $current_ascii = ord($string{$i}); // convert to ascii code if($current_ascii>64 && $current_ascii<91){ // check for upper case character $toggled_string .= chr($current_ascii+32); // replace with lower case character }elseif($current_ascii>96 && $current_ascii<123){ // check for lower case character $toggled_string .= chr($current_ascii-32); // replace with upper case character }else{ $toggled_string .= $string{$i}; // concatenate the non alphabetic string. } } echo "The toggled case letter for $string is <hr />".$toggled_string; // output will be mYdONS - hELPS mAKE bETTER ?>
The post How to toggle character case in PHP without strlower, strupper & ucfirst (inbuilt) and Array function appeared first on Mydons.