How to use Loop and ctype Functions In PHP

Another approach involves iterating through each character in the string and using ctype functions to check their types.

PHP
<?php 
function checkChars($str) { 
    $upperCase = $lowerCase = $specialChar = $numericVal = false; 

    for ($i = 0; $i < strlen($str); $i++) { 
        if (ctype_upper($str[$i])) { 
            $upperCase = true; 
        } else if (ctype_lower($str[$i])) { 
            $lowerCase = true; 
        } else if (ctype_digit($str[$i])) { 
            $numericVal = true; 
        } else { 
            $specialChar = true; 
        } 
    } 

    return [ 
        'Uppercase' => $upperCase, 
        'Lowercase' => $lowerCase, 
        'Special Characters' => $specialChar, 
        'Numeric Values' => $numericVal, 
    ]; 
} 

// Driver code 
$str = "w3wiki123@#$"; 
$result = checkChars($str); 

foreach ($result as $type => $hasType) { 
    echo "$type: " . ($hasType ? 'Yes' : 'No') . "\n"; 
} 
?> 

Output
Uppercase: Yes
Lowercase: Yes
Special Characters: Yes
Numeric Values: Yes


PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values

Given a String, the task is to check whether the given string contains uppercase, lowercase, special characters, and numeric values in PHP. When working with strings in PHP, it’s often necessary to determine the presence of certain character types within the string, such as uppercase letters, lowercase letters, special characters, and numeric values.

Examples:

Input: str = "w3wiki123@#$" 
Output: Yes 
Explanation: The given string contains uppercase 
characters('G', 'F'), lowercase characters('e', 'k', 's', 'o', 'r'), 
special characters( '#', '@'), and numeric values('1', '2', '3'). 
Therefore, the output is Yes. 
 
Input: str = "w3wiki" 
Output: No 
Explanation: The given string contains only uppercase 
characters and lowercase characters. Therefore, the 
output is No.

here are some common approaches:

Table of Content

  • Using Built-in Functions
  • Using Loop and ctype Functions
  • Using filter_var and Custom Validation

Similar Reads

Using Built-in Functions

PHP provides several built-in functions that help determine the presence of specific character types in a string....

Using Loop and ctype Functions

Another approach involves iterating through each character in the string and using ctype functions to check their types....

Using filter_var and Custom Validation

This approach uses filter_var in combination with custom validation logic to check for the presence of uppercase, lowercase, special characters, and numeric values....

Contact Us