Home » Php » PHP: is empty($var) equivalent to !$var

PHP: is empty($var) equivalent to !$var

Posted by: admin July 12, 2020 Leave a comment

Questions:

For validating a variable value we can do

if(empty($var)){
}

OR

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

if(!$var){
}

What is the difference between this two approaches, are them equivalent?

EDIT: Some examples where they behave different will be more pratical.

EDIT2: The only difference founded from answers is that the second will throw a notice if $var is undefined. What about the boolean value they return?

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

Conclusion from users answers:
if(!$var) and empty($var) are equivalent as described here http://php.net/manual/en/types.comparisons.php, they will return the same bool value on the same variable.

if(!$var) will return a php notice if $var is not defined, normally this is not the case (if we write good code) most IDEs will underline it.

  • When checking simple variables if(!$var) should be ok
  • When checking arrays index ($var[‘key’]) or object properties ($var->key)
    empty($var['key']) is better using empty.
How to&Answers:

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

You prefer the first one because it is a “shorter way”?
Shorter code does not mean better code, or faster scripts 😉

The speed of PHP functions and its various other behaviours is not determined by the length of the function name. It is determined by what PHP is actually doing to evaluate, action, and return results.

Besides that, don’t choose methods based on length of code, choose methods based on scenario and best approach “for a given scenario“.
Which is best depends on what you need, and there are other variable checks other than the two you mentioned (isset() for one).

but the problem is are they equivalent always

Not necessarily – see
http://php.net/manual/en/types.comparisons.php

Or create a quick test script to see what PHP returns for your two scenarios.

You could also be initialising your variables in your framework (or, likely, stand alone script), which means the scenario changes, as could your question and approach you use.

It’s all contextual as to which is the best.

As for the required answer.

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

(!$vars)

Example code:

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

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

However, if you initialise the var in your scripts somewhere first:

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

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

$vars = "anything";

will return:
FALSE

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

When we initialise it with a string then the var NOT being FALSE is FALSE.

empty($vars)

Example code:

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

Not initialised/set at all, and all of the following:

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

will return:
TRUE

There is no PHP notice for using empty, so here we show a difference between the two options (and remember when I said the shortest code is not necessarily the “best”? Depends on the scenario etc.).

And as with the previous test:

$vars = "anything";

returns:
FALSE

This is the same with ( !$var ), you are testing IF EMPTY, and without the var being initialised at all, or with any “empty()” value: eg (“”), or NULL, or zero (0), then testing if the var is empty is TRUE, so we get TRUE output.

You get FALSE when setting the var to a string because IS EMPTY = FALSE as we set it to something.


The difference is empty() does not throw a PHP notice when var is not defined, whereas (!$var) will.

Also, you may prefer it for being “shorter code”, but if (!$var) isn’t really much shorter/better looking than the widely used if (empty($var)).

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

Answer:

No they are not equal

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


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

will output

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

Following values are considered to be empty when using empty() function

  • “” (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; (a variable declared, but without a value)

As you can read in empty docs

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

Answer:

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

In older versions of PHP, empty() only worked on direct variables, meaning this would fail:

empty($a && $b);

This has been changed in 5.5

Answer:

They are not.
The first one verify if $var has any value.
The second one verify as boolean – if true or not.

The second one will give you a notice, the first one will be true if the value is empty for $var.

If you wish to verify 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 notice

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

Answer:

The official manual contains all you have to know on this subject:

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

if (!$var) is the last column, boolean : if($x) negated.

As you can see they are the same, but empty won’t complain if the variable wasn’t set.

From the manual:

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

Take some time, and study that chart.

Answer:

As far as I know, it’s pretty simple.

empty() is basically equivalent to !isset($var) || !$var and does not throw any warnings/notices, whereas using just !$var will throw a notice if the variable isn’t defined.

code and log
output

For the sake of completeness, the following are considered empty when using empty():

  1. empty strings
  2. empty arrays
  3. 0, 0.0, '0' (int, float, string)
  4. null
  5. false
  6. defined variables without a value

Answer:

From a boolean value return empty is equivaliend to !:

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

From a notice/waning notification 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