PHP Check if all characters are lower case
Last Updated :
18 Jul, 2024
Improve
Given a string, check if all characters of it are in lowercase.
Examples:
Input : gfg123
Output : No
Explanation : There are characters
'1', '2' and '3' that are not lower-
case
Input : geeksforgeeks
Output : Yes
Explanation : The string "geeksforgeeks"
consists of all lowercase letters.
Below we are some common methods to check if all characters are lower case
Table of Content
Using ctype_lower()
In this approach we are using ctype_lower in PHP to check if each string in an array contains only lowercase characters. The function returns true if all characters are lowercase, otherwise false. This efficiently validates the case of characters within each string.
Example:
<?php
// PHP program to check if a string has all
// lower case characters
$strings = array('gfg123', 'geeksforgeeks', 'GfG');
// Checking for above three strings one by one.
foreach ($strings as $testcase) {
if (ctype_lower($testcase)) {
echo "Yes\n";
} else {
echo "No\n";
}
}
?>
Output
No Yes No
Using a Regular Expression with preg_match()
The preg_match() function in PHP can be used to check if a string matches a specific pattern. In this case, we can use a regular expression to determine if all characters in the string are lowercase letters.
Example:
<?php
// Function to check if all characters in a string are lowercase
function all_lowercase($string) {
return preg_match('/^[a-z]+$/', $string) === 1;
}
// Test array of strings
$strings = ["gfg123", "geeksforgeeks", "GeeksForGeeks"];
// Iterate through the array and check each string
foreach ($strings as $str) {
if (all_lowercase($str)) {
echo "Yes\n";
} else {
echo "No\n";
}
}
?>
Output
No Yes No