Home » Php » should i use empty() php function

should i use empty() php function

Posted by: admin July 12, 2020 Leave a comment


which is better?

if (!empty($val)) { // do something }


if ($val) { // do something }

when i test it with PHP 5, all cases produce the same results. what about PHP 4, or have any idea which way is better?

How to&Answers:

You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead.

empty() is the equivalent of !isset($var) || $var == false. It returns true if the variable is:

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


Read the manual:

empty() is the opposite of (boolean) var, except that no warning is
generated when the variable is not set.