I have to use the empty () php function

what's better?

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

and

 if ($val) { // do something } 

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

+6
source share
2 answers

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

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

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

Read the manual:

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

0
source

Source: https://habr.com/ru/post/896337/


All Articles