Is empty() enough or use isset()?
Asked Answered
S

6

24

Note - I know pretty much about empty() and isset(), what I am asking is the most proper/efficient way of using them.

I've just saw at php.net this sentence under empty() reference:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

But again, as I'm mainly working now on other people's apps (either standalone projects, websites using cms or even frameworks) many many times I've seen people writing:

if (isset ($var) && $var != '')
// or
if (isset ($var) && !empty($var))

(mainly with $_GET and $_POST variables, but not only)

As far as I understand manual, snippet below is equivalent:

if (!empty($var))

Or am I missing something? What is technically the best way to check existense of variable with value?

I know both functions, their destinations. I just want to know if empty() is all needed to check if is variable set and given value. I know that it works, but is it 100% proper and safe?

Southwestwardly answered 9/12, 2014 at 14:2 Comment(6)
empty() is preferred wayHarrisharrisburg
I am always use empty, because I do not need to check, is it set or not, but be carefull! For example, if you want to validate a text input, and I need to be sure, it's just filled, does not matter what is in it, use isset and strlen because 0 will return true for empty.Asco
And anyway, isset($v) && $v is full equivalent of !empty($v)Berl
Your cms examples are highly context dependent. For example if variable is $var = '0', var_dump(isset ($var) && $var != '') is not the same as var_dump(!empty($var)). You should be careful when comparing strings with other types.Makkah
This comparison table helps.Skald
@DigitalChris thanks! never seen it :)Southwestwardly
A
19

Op codes generated from isset($var) && !empty($var)

line     #  *  op                           fetch           ext  return  operands
---------------------------------------------------------------------------------


   3     0  >   EXT_STMT                                                 
         1      ISSET_ISEMPTY_VAR                      12800000    ~0       !0
         2  >   JMPZ_EX                                      ~0    ~0,     ->6
         3  >   ISSET_ISEMPTY_VAR                      11800000    ~1       !0
         4      BOOL_NOT                                     ~2    ~1
         5      BOOL                                         ~0    ~2
         6  >   FREE                                               ~0
   4     7  >   RETURN                                              1

and from !empty($var)

line     #  *  op                           fetch           ext  return  operands
---------------------------------------------------------------------------------
   3     0  >   EXT_STMT                                                 
         1      ISSET_ISEMPTY_VAR                      11800000    ~0       !0
         2      BOOL_NOT                                           ~1       ~0
         3      FREE                                                        ~1
   4     4  >   RETURN                                                       1

So yes it does repeat ISSET_ISEMPTY_VAR but !$empty. It depends on the value passed, but it it doesnt exist the top way is one opcode less BOOL_NOT. but if it does exist, the bottom way is quicker.

Though its unlikely this is going to be a bottleneck in any application

Anthology answered 9/12, 2014 at 14:22 Comment(0)
P
14

empty is sufficient, but beware of its consequences.

If $var is one of 0, '0', false, '', [], null (and perhaps a few others I forgot), then it will be considered isset certainly, but it will also be empty. Note that string '0' is a particular gotcha.

Personally I only use isset. If a value is required to be non-empty, I will then check that separately and throw an error (which is caught by suitable error-handling blocks) to give the user a simple, precise "this value is required" error.

Polynesia answered 9/12, 2014 at 14:9 Comment(6)
What is NaN in php?Berl
NaN does not exist in php, only javascript ;-)Exclusion
Yup, you forgot that 0.0 is empty too :P and common understanding of NaN is a value that is not a number, but still value (especially in PHP where where float variable can be string later on).Southwestwardly
Ah, PHP spells it as NAN and has it as a case-sensitive constant. Even spelled right, empty(NAN) is false... hmm...Polynesia
@NiettheDarkAbsol As I said a comment above, NAN is stilla a value. And as for your Answer, I think it gave me enough to think about :)Southwestwardly
@NiettheDarkAbsol, it's close to the same reason that "0" is falsey but "0.0" isn't. Because that's what PHP used to do, and wants to deal with changing.Meier
E
4

isset will simply tell you if the variable is set, regardless of the value (null, false etc).

If you want to test the value is not a blank string, null, false or 0 use empty.

Exclusion answered 9/12, 2014 at 14:8 Comment(2)
does isset mean exists?Rota
@Rota it means variable is declared and is not nullSouthwestwardly
W
3

If you use !(empty($var) then the variable is set and contains a value which can be empty like "" or null or 0.

if(!empty($_COOKIE['dev'])) echo 'developer mode';

If the cookie is there, either empty or filled with any value, the condition is true. Else it will be ignored.

That is useful if you work with arrays and do not know if the key is set to avoid warnings.

Waterfall answered 9/12, 2014 at 14:21 Comment(0)
B
3

When you evaluate $_POST and $_GET the difference between isset and isempty is usefull. As you said not empty() var means that isset AND the value as been sent.

So

if (!empty($var))

is ceratinly enough for

if (isset ($var) && $var != '')

what are you missing is just that sometimes

if (isset($var)) {
  if ($var != '') {

  } else {
    ... do "A"
  }
} else {
  ... do something different from "A"
}

you may need this. And if this happens often, when it won't you'll just merge the two if conditions and forget about empty(). As you already found. I think that using just "empty" may be faster but internally probably it does the same checks.

Bolte answered 9/12, 2014 at 14:30 Comment(0)
W
2

GET/POST/COOKIE variables should be checked with filter_input function. This function can check if the specified key is present in the input (GET/POST/COOKIE/etc) and optionally filter it. Example:

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
/*
 * QUERYSTRING           RESULT
 * ==================    ===============
 * test.php?             $id is NULL
 * test.php?id=          $id is FALSE
 * test.php?id=123abc    $id is FALSE
 * test.php?id=123       $id is int(123)
 */
if ($id !== NULL && $id !== FALSE) { /*...*/ }

The empty() function on the other hand simply checks if a variable is not set or its value is falsy. This function cannot be used in situations where falsy values make sense:

if (empty($_GET["number_of_children"])) {
    /*
     * GET parameter is not set or its value is zero or falsy
     * Show an error? Or process the value?
     */
}
if (empty($_GET["number_of_children"]) === false) {
    /*
     * Definitely a truthy value
     * But how does one specify that he/she has no children?
     */
}
Weissberg answered 9/12, 2014 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.