Better way to check variable for null or empty string?


Question

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?

I want to ensure that:

  1. null is considered an empty string
  2. a white space only string is considered empty
  3. that "0" is not considered empty

This is what I've got so far:

$question = trim($_POST['question']);

if ("" === "$question") {
    // Handle error here
}

There must be a simpler way of doing this?

1
165
12/19/2008 4:01:18 PM

Accepted Answer

// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}
264
6/14/2018 4:58:21 AM

Old post but someone might need it as I did ;)

if (strlen($str) == 0){
do what ever
}

replace $str with your variable. NULL and "" both return 0 when using strlen.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon