Php – defining an empty variable

PHPstring

suppose

$test = '';

if(empty($test)){ $test = "not found";}

echo $test;

the above case the answer will be "not found"

but below one even though the $test variable is empty but result give nothing.

$test = ' ';

if(empty($test)){ $test = "not found";}

echo $test;

how we can treat both these variables as empty in PHP??

Best Answer

$test = ' ' is not empty. From the details in the documentation:

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

If you want to test if $test is only white space characters, see these questions:

If string only contains spaces?
How to check if there are only spaces in string in PHP?