How to check if a string is blank (empty, null, or contains only whitespace) in PHP

1 Answer

0 votes
function isBlankOrEmpty($str) {
    // Check for null or empty string
    if ($str === null || $str === "") {
        return true;
    }

    // Check if the string contains only whitespace
    foreach (str_split($str) as $ch) {
        if (!ctype_space($ch)) {
            return false; // Found a non-whitespace character
        }
    }
    
    return true;
}

$testCases = [null, "", "   ", "abc"];

foreach ($testCases as $index => $test) {
    echo "Test" . ($index + 1) . ": " . (isBlankOrEmpty($test) ? "true" : "false") . "\n";
}



/*
run:

Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 7 by avibootz
...