298

Is there a difference between isset and !empty. If I do this double boolean check, is it correct this way or redundant? and is there a shorter way to do the same thing?

isset($vars[1]) AND !empty($vars[1])
Dan Lugg
  • 20,192
  • 19
  • 110
  • 174
silow
  • 4,256
  • 3
  • 21
  • 24
  • 3
    There is a nice chart on the results of using them with different types of variables (they do have differences) here: https://www.virendrachandak.com/demos/php-isset-vs-empty-vs-is_null.php – Jeff Clayton Dec 14 '16 at 17:06
  • The obvious exact complements are isset and is_null, but !empty covers a few different ones. It all depends on the type of data you are testing for. – Jeff Clayton Dec 14 '16 at 17:34

10 Answers10

461

This is completely redundant. empty is more or less shorthand for !isset($foo) || !$foo, and !empty is analogous to isset($foo) && $foo. I.e. empty does the reverse thing of isset plus an additional check for the truthiness of a value.

Or in other words, empty is the same as !$foo, but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.

The manual puts it like this:

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

You can simply use !empty($vars[1]) here.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 13
    But then if there is no `$vars[1]` he'll get a notice. – karim79 Dec 30 '10 at 04:22
  • 6
    I've no idea where I got that idea from. Plus one'd. – karim79 Dec 30 '10 at 04:27
  • 10
    @karim IMO `empty` is one of the most misunderstood functions in PHP. The tiny snippet about "no warning is generated" is very easy to overlook. I had to scan the documentation myself a few times to spot it to post it here. – deceze Dec 30 '10 at 04:29
  • 2
    `empty($vars[1])` doesn't cause any warnings even `$vars[1]` is not set, but `echo $vars[1]` will. I checked the fact using `echo $vars[1]; if (!empty($vars[1])) echo 1; else echo 0;`. – Amil Waduwawara Dec 30 '10 at 05:44
  • @AmilWaduwawara - Yes. Your snippet behaves as expected, you star with an echo statement. I imagine you get the warning then the 0. – Stephane Gosselin Nov 28 '13 at 22:34
  • Most answers here are wrong as far as I can tell. The 2 are not the same when a variable is set AND empty. `isset` returns true and `empty` returns false. Doesn't matter if it's a string or an array. So any test that wants to know if a variable exists and is not empty, or the opposite, needs to use both – fred Jul 09 '16 at 19:27
  • 3
    @fred Uhm, no. The "isset and empty" ("isset *but* empty") is covered by `isset($var) && !$var`. But this test also has a false negative if you're testing the value `null`, so is not reliable and therefore largely not applicable in practice. What you write at the end, "exists and is not empty", is simply `!empty`. I'm not sure what exactly "the opposite" is, so here's both: "not exists and is empty" → `!isset` (again: false negatives), "not exists or is empty" → `empty`. – deceze Jul 10 '16 at 07:12
  • 2
    @fred Always write out `empty` in its logical long form `!isset($var) || $var == false` and you'll see that it's *always* redundant in any combination of `isset` together with `empty`. – deceze Jul 10 '16 at 07:15
  • Except it doesn't really work because when your value is 0 it is considered as empty and its obviously not the case. So thanks PHP for having a good API, I guess. #not – Shahor Nov 23 '16 at 12:21
  • 3
    @Shahor That *works* as intended. That `0` is a falsey value in PHP is something you have to be aware of, it's not just `empty` that treats it that way. – deceze Nov 23 '16 at 12:28
  • @deceze I know it works that way, I just don't like that fact in the language. – Shahor Nov 28 '16 at 17:00
  • 5
    @Shahor *Many* languages regard `0` as `false`. PHP isn't the only one. Still not sure what your complaint is. – deceze Nov 28 '16 at 17:02
  • 2
    `empty()` will *still* throw a warning for nested variables. For instance, this code will throw a warning: `empty($unsetvar1[$unsetvar2['test']]);` – Aaron Cicali May 17 '18 at 15:27
  • 1
    @karim79 @deceze I think that at one point, using `empty` on a variable that didn't exist would have generated a warning. In the mid 2000s to the early 2010s, a lot of PHP code that I worked on used `isset(var) && !empty(var)` as a truth test. In fact I did that out of habit for so long that I arrived at this page today while searching to make sure I didn't need to anymore. – felwithe May 29 '18 at 00:38
  • 1
    @felwithe I just looked at the PHP 4 & 3 manuals, and even they already mention `empty` not generating any warnings. – deceze May 29 '18 at 07:42
  • 1
    This is simply not true and the accepted answer should be ignored! Learn more: https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/ https://www.geeksforgeeks.org/why-to-check-both-isset-and-empty-function-in-php/ – madjoe Jul 26 '19 at 14:11
  • @madjoe You'll have to be more specific what exactly "isn't true" here. – deceze Jul 26 '19 at 14:16
  • @deceze I suggest to delete the first sentence where the author of the proposed answer suggests isset and !empty as redundant, which is not the case. Later he explains the correlation between the two, but someone may get the impression we should choose only one to avoid "redundancy". Check both links in my comment above. – madjoe Jul 26 '19 at 14:23
  • 1
    @madjoe The question is whether one should use `isset() && !empty()` *together*. And the correct answer is that this is entirely redundant. Not sure what you're against exactly. – deceze Jul 26 '19 at 14:26
  • @deceze: If you use `isset($var) && !empty($var)` and if we assign any one of the following elements to $var = {” ” (space), TRUE, NULL byte (“\ 0”)}, it will always return TRUE. On the other hand, `isset()` alone would return TRUE for different and a bigger set of values for $var. Therefore, how could it be redundant? – madjoe Jul 26 '19 at 14:34
  • 1
    @madjoe Because the `!empty` check is a superset of what `isset` does. You're essentially checking `isset($var) && isset($var) && $var != false`. And that's redundant. You can leave out the `isset`. – deceze Jul 26 '19 at 14:36
  • 1
    @deceze: Ok, you are right. I completely misunderstood your point from the beginning, I apologize. – madjoe Jul 26 '19 at 14:39
  • isset() can be lenght 0 and returns true, but !empty() check has some value in it ...so is good to have both. when you are passing variables via post for example – vincent thorpe Sep 13 '20 at 13:20
  • 1
    @vincentthorpe It’s good to have both functions available, sure, but there’s never a case where using them together makes any sense. – deceze Sep 13 '20 at 15:33
  • @deceze when it comes to arrays it still shows `Notice` : https://i.imgur.com/hctFlnz.png OR am I missing something? – Binod Kalathil Oct 29 '20 at 16:13
  • @Binod Can’t say anything about that from that screenshot alone. – deceze Oct 29 '20 at 16:39
  • @deceze `!empty` to an undefined key of an array really is throwing `Notice` which seems we need to use `isset($vars[1]) AND !empty($vars[1])` instead of just `!empty($vars[1])` right? – Binod Kalathil Oct 29 '20 at 16:44
  • @Binod That should not be the case. Please provide a self-contained example, e.g. at http://3v4l.org. I’d guess you have a custom error handler which gets invoked (yes, even when using `empty`), which is indiscriminately producing exceptions. – deceze Oct 29 '20 at 17:20
  • @deceze There is a logical error in that line itself. lol. https://i.imgur.com/hctFlnz.png. This first `empty` actually doesnt just wrap the array reference. :) – Binod Kalathil Nov 05 '20 at 15:47
35

isset() tests if a variable is set and not null:

http://us.php.net/manual/en/function.isset.php

empty() can return true when the variable is set to certain values:

http://us.php.net/manual/en/function.empty.php

To demonstrate this, try the following code with $the_var unassigned, set to 0, and set to 1.

<?php

#$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>
samayo
  • 16,163
  • 12
  • 91
  • 106
GreenMatt
  • 18,244
  • 7
  • 53
  • 79
18

isset($vars[1]) AND !empty($vars[1]) is equivalent to !empty($vars[1]).

I prepared simple code to show it empirically.

Last row is undefined variable.

+-----------+---------+---------+----------+---------------------+
| Var value | empty() | isset() | !empty() | isset() && !empty() |
+-----------+---------+---------+----------+---------------------+
| ''        | true    | true    | false    | false               |
| ' '       | false   | true    | true     | true                |
| false     | true    | true    | false    | false               |
| true      | false   | true    | true     | true                |
| array ()  | true    | true    | false    | false               |
| NULL      | true    | false   | false    | false               |
| '0'       | true    | true    | false    | false               |
| 0         | true    | true    | false    | false               |
| 0.0       | true    | true    | false    | false               |
| undefined | true    | false   | false    | false               |
+-----------+---------+---------+----------+---------------------+

And code

$var1 = "";
$var2 = " ";
$var3 = FALSE;
$var4 = TRUE;
$var5 = array();
$var6 = null;
$var7 = "0";
$var8 = 0;
$var9 = 0.0;

function compare($var)
{
    print(var_export($var, true) . "|" .
        var_export(empty($var), true) . "|" .
        var_export(isset($var), true) . "|" .
        var_export(!empty($var), true) . "|" .
        var_export(isset($var) && !empty($var), true) . "\n");
}

for ($i = 1; $i <= 9; $i++) {
    $var = 'var' . $i;
    compare($$var);
}

@print(var_export($var10, true) . "|" .
    var_export(empty($var10), true) . "|" .
    var_export(isset($var10), true) . "|" .
    var_export(!empty($var10), true) . "|" .
    var_export(isset($var10) && !empty($var10), true) . "\n");

Undefined variable must be evaluated outside function, because function itself create temporary variable in the scope itself.

Jsowa
  • 9,104
  • 5
  • 56
  • 60
13

The accepted answer is not correct.

isset() is NOT equivalent to !empty().

You will create some rather unpleasant and hard to debug bugs if you go down this route. e.g. try running this code:

<?php

$s = '';

print "isset: '" . isset($s) . "'. ";
print "!empty: '" . !empty($s) . "'";

?>

https://3v4l.org/J4nBb

Snowcrash
  • 80,579
  • 89
  • 266
  • 376
8
$a = 0;
if (isset($a)) { //$a is set because it has some value ,eg:0
    echo '$a has value';
}
if (!empty($a)) { //$a is empty because it has value 0
    echo '$a is not empty';
} else {
    echo '$a is empty';
}
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
rajmohan
  • 1,618
  • 1
  • 15
  • 36
3

Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy

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

while isset check if the variable isset and not null which can also be found in the php doc(isset)

Breezer
  • 10,410
  • 6
  • 29
  • 50
2

It is not necessary.

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

php.net

madlopt
  • 415
  • 4
  • 7
  • 2
    This has never been necessary on any PHP version, since empty already checks for (not) isset. You are confusing the fact that empty now supports expressions with the question. – alxgb Jan 02 '16 at 23:42
  • It is only true, five years later. – Lennon Dec 17 '18 at 18:28
1
  • From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

  • Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

Ende
  • 303
  • 2
  • 4
  • 24
0

"Empty": only works on variables. Empty can mean different things for different variable types (check manual: http://php.net/manual/en/function.empty.php).

"isset": checks if the variable exists and checks for a true NULL or false value. Can be unset by calling "unset". Once again, check the manual.

Use of either one depends of the variable type you are using.

I would say, it's safer to check for both, because you are checking first of all if the variable exists, and if it isn't really NULL or empty.

Stuart
  • 446
  • 1
  • 6
  • 19
  • 3
    @szahn "safer to check for both", - you as programmer can check everything you want for the safety. But if your code is redundant then you can be redundant as programmer. – madlopt Apr 19 '16 at 13:51
-1

if we use same page to add/edit via submit button like below

<input type="hidden" value="<?echo $_GET['edit_id'];?>" name="edit_id">

then we should not use

isset($_POST['edit_id'])

bcoz edit_id is set all the time whether it is add or edit page , instead we should use check below condition

!empty($_POST['edit_id'])
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • previous post was submitted bcoz i press enter by mistake, here is my complete answer...why downvote? :( – xkeshav Dec 30 '10 at 07:16