PHP: empty ($ var) equivalent! $ Var

To check the value of a variable, we can do

if(empty($var)){
}

      

OR

This will return true on an empty string, 0 as a number, false, null

if(!$var){
}

      

What is the difference between these two approaches, are they equivalent?

EDIT . Some examples when they behave differently will be more rational.

EDIT2 . The only difference based on the answers is that the second will trigger a notification if $ var is undefined. How about a boolean return value?

EDIT3 : For $ var, I mean any variable with any value, or even undefined variable.

Conclusion from user answers : if(!$var)

and are empty($var)

equivalent as described here http://php.net/manual/en/types.comparisons.php , they will return the same bool value in the same variable.

if(!$var)

will return a php notification, if $var

not defined, usually it is not (if we write good code), most IDEs will underline it.

  • When checking simple variables it if(!$var)

    should be ok
  • When checking array index ($ var ['key']) or object properties ($ var-> key) empty($var['key'])

    it is better to use empty.
+3


source to share


7 replies


From a boolean value, return empty is equivalent to !:

empty($var) === !$var; // supposed that $vars has been defined here

      



From a notification / decay notice, they are not equivalent:

empty($array['somekey']); //will be silent if somekey does not exists
!$array['somekey']; // will through a warning if somekey does not exists

      

0


source


the problem is that since! $ vars is shorter than empty ($ vars), many of us will prefer the first way

Do you prefer the former because it is the "shorter route"?
Shorter code doesn't mean better code or faster scripts!

The speed of PHP functions and their other behaviors is not determined by the length of the function name. This is determined by what PHP actually does to evaluate, action, and return results.

Also, do not choose methods based on code length, choose methods based on the scenario and the best "for the given scenario" approach.
What is best depends on what you need and there are other validation variables other than the two you mentioned ( isset()

for one).

but the problem is that they are always equivalent

No, and there are many other answers on Stack, Google and php.net - AKA PHP Guide!
http://php.net/manual/en/types.comparisons.php

Or you could just create a quick test script to see what PHP returns for your two scripts.

All this is why I wondered why there are 6 upvotes ...

Adding all of this, you can also initialize your variables in your structure (or probably in a standalone script), which means the script changes, just like your question and the approach you are using.

Everything is contextual, which is best.

As for the required answer.

Anyway, to answer your question, here are some tests:

(!$vars)

Sample code:

if ( !$vars )
 {
  echo "TRUE";
 }
else
 {
  echo "FALSE";
 }

      

will return:
Note: variable Undefined: vars in / whatever / on line X
TRUE

However, if you initialize var in your scripts first:

$vars = "";
$vars = NULL;
$vars = 0;

      

Any of the above will return:
[no PHP notification]
TRUE



$vars = "anything";

      

will return:
FALSE

This is because with the exclamation mark you are testing if var is FALSE, so when not initialized with a string, the test script returns TRUE because it is NOT FALSE.

When we initialize it with a string, then var NOT FALSE is FALSE.

empty($vars)

Sample code:

if ( empty($vars) )
 {
  echo "TRUE";
 }
else
 {
  echo "FALSE";
}

      

Not initialized / installed at all, and all of the following:

$vars = "";
$vars = NULL;
$vars = 0;

      

will return:
TRUE

There is no PHP notification of using empty, so here we show the difference between the two (and remember when I said that the shortest code is not necessarily the "best", depends on the script, etc.).

And as in the previous test:

$vars = "anything";

      

returns:
FALSE

It's the same with ( !$var )

, you test IF EMPTY and without initializing var at all or with any value " empty()

": for example ("") or NULL or zero (0), then testing if var is empty is TRUE, so we get TRUE.

You get FALSE when we set var to a string, because IS EMPTY = FALSE when we set it.


The difference is empty()

not throwing a PHP notification when var is not defined then it (!$var)

will.

Alternatively, you might prefer it for "shorter code", but I think it if ( !$var )

looks ugly and not as easy to look at as if ( empty($var) )

.
But again, this depends on the scenario - PHP provides different options to suit different requirements.

+4


source


No they are not equal

if(empty($var)){
  echo "empty used\n";
}


if(!$var){ # line no. 6
  echo "! used";
}

      

deduces

empty used
Notice: Undefined variable: var in /var/www/html/test.php on line 6
! used

      

The following values ​​are considered empty when using the empty () function

  • "" (empty line)
  • 0 (0 as integer)
  • 0.0 (0 as float)
  • "0" (0 as string)
  • NULL
  • FALSE
  • array () (empty array)
  • $ var; (declared variable, but no value)

As you can read the empty docs

empty () is essentially the shorthand equivalent! isset ($ var) || $ var == false.

+3


source


The main difference is that empty () will not complain if a variable does not exist, whereas using! will generate a warning.

In older versions of PHP, empty () only works on direct variables, which means it won't work:

empty($a && $b);

      

This was changed in version 5.5

+1


source


This is not true. The first one checks if $ var has any value. The second is checked as boolean - if true or not.

In the second case, you will receive a notification, the first will be true if the value is empty for $ var.

If you want to check if $ var exists, use isset.

if( !isset($var) )
    echo '$var does not exists!<br>';

if(empty($var))
    echo 'The value is empty or does not exists!<br>';

if( !$var )
    echo 'Value is false!<br>';

$var = '';
if(empty($var))
    echo 'The value is empty or does not exists!<br>';

      

Use this to view the notification

error_reporting(-1);
ini_set('display_errors', 1);

      

+1


source


The official guide contains everything you need to know on this subject:

http://php.net/manual/en/types.comparisons.php

if (!$var)

- the last column is boolean : if($x)

negated.

As you can see they are the same, but empty

it won't complain if a variable hasn't been set.

From the manual:

empty() does not generate a warning if the variable does not exist

      

Take some time and study this diagram.

+1


source


As far as I know, this is pretty simple.

empty()

is basically equivalent !isset($var) || !$var

and doesn't raise any warnings / notifications, whereas using !$var

will only raise a notification if the variable is undefined.

code and logoutput

For completeness, these empty()

are considered empty when used :

  • blank lines
  • empty arrays
  • 0

    , 0.0

    , '0'

    (Int, float, string)
  • null

  • false

  • defined variables without meaning
+1


source







All Articles