How to check if a variable is null or empty in PHP

1 Answer

0 votes
function IsNullOrEmptyString(string|null $str){
    return $str === null || trim($str) === '';
}

$str = "";
echo IsNullOrEmptyString($str) ? "yes" : "no";

echo "\n";

$str = null;
echo IsNullOrEmptyString($str) ? "yes" : "no";

echo "\n";

$str = "php";
echo IsNullOrEmptyString($str) ? "yes" : "no";



/*
run:

yes
yes
no

*/

 



answered Jul 25, 2024 by avibootz
...