What is the difference between if(!$variable)
and if(isset($variable))
?
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.
The isset function in PHP is used to determine whether a variable is set or not. A variable is considered as a set variable if it has a value other than NULL. In other words, you can also say that the isset function is used to determine whether you have used a variable in your code or not before.
"isset() checks if a variable has a value including (False, 0 or empty string), but not NULL.
Well, the answer is pretty simple. isset($var)
returns whether or not a variable exists and is not null, where !$var
tells you if that variable is true
, or anything that evaluates to true
(such as a non-empty string). This is summarized in the first table of this documentation page.
Also, using !$var
will output a notice that you're using an undefined variable, whereas isset($var)
won't do that.
Mind you, they are two different things:
<?php
var_dump( isset($foo) ); // false.
var_dump( !$foo ); // true, but with a warning.
$foo = false;
var_dump( isset($foo) ); // true
var_dump( !$foo ); // true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With