![php_logo_128]()
Toggling between upper and lower case letter is quite challenging. There is a PHP inbuilt function's which can do this operation
PHP: strtoupper - Manual ,
PHP strtolower() Function &
PHP: ucfirst - Manual , the real challenge would be you have to toggle case of the given word without using PHP built in function and Array function. You might have got a chance to solve these kind of programs in the interview, some will succeed and some will fail. Toggling between character case can be achieved in simpler way and steps are shown below,
- 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
The below code snippets shows the PHP code to toggle character case without Array and strlower, strupper & ucfirst (inbuilt) function.
<?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
?>