PHP function Exercises: Checks whether a string is all lower case
PHP function: Exercise-5 with Solution
Write a PHP function that checks whether a string is all lower case.
Visual Presentation:
Sample Solution:
PHP Code:
<?php
// Define a function to check if a string is all lowercase
function is_str_lowercase($str1)
{
// Iterate through each character in the string
for ($sc = 0; $sc < strlen($str1); $sc++) {
// Check if the character's ASCII value is within the uppercase range
if (ord($str1[$sc]) >= ord('A') &&
ord($str1[$sc]) <= ord('Z')) {
return false; // If any uppercase character is found, return false
}
}
return true; // If no uppercase characters are found, return true
}
// Test the function with sample strings and display the results
var_dump(is_str_lowercase('abc def ghi')); // Output: bool(true) (all lowercase)
var_dump(is_str_lowercase('abc dEf ghi')); // Output: bool(false) (uppercase 'E' found)
?>
Output:
bool(true) bool(false)
Explanation:
In the exercise above,
- The function "is_str_lowercase()" takes a string '$str1' as input.
- It iterates through each character of the input string using a for loop.
- Within the loop, it checks if the ASCII value of the current character falls within the uppercase range ('A' to 'Z') using the "ord()" function.
- If any character is found to be uppercase, the function returns 'false', indicating that the string is not all lowercase.
- If no uppercase characters are found after iterating through the entire string, the function returns 'true', indicating that the string is all lowercase.
- The "var_dump()" function tests the "is_str_lowercase()" function with two sample strings: 'abc def ghi' (which is all lowercase) and 'abc dEf ghi' (which contains an uppercase 'E'). The results are displayed.
- Based on the results, the first call returns 'bool(true)' indicating that the string is all lowercase, while the second call returns 'bool(false)' indicating that the string contains an uppercase character.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a function to sort an array.
Next: Write a PHP function that checks whether a passed string is a palindrome or not?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-function-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics