Better way to check variable for null or empty string?

Allain Lalonde picture Allain Lalonde · Dec 19, 2008 · Viewed 251.2k times · Source

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?

Answer

Michael Haren picture Michael Haren · Dec 19, 2008
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}