While I believe the answer is yes, I have seen the following in legacy code so much, I'm doubting myself. I'm asking for a sanity check from the community.
if (is_null($result) || !$result) {
if (!$result) {
Note: I am aware this will throw a Notice if $result
is not set.
Is this code logically equivalent?
I tested with all the combinations of PHP false values without receiving Not equal for ....
$false_values = array(false, 0, 0.0, '0', '', null, array(), new stdClass());
foreach ($false_values as $var) {
if (!$var != (is_null($var) || !$var)) {
echo 'Not equal for: ';
var_dump($var);
}
}
$ php check.php
$
The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.
Definition and Usage 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.
Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.
The isset() function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not.
A null
variable will evaluate to false
in a boolean context. So the statements are logically equivalent - when the variable is null it will be caught by the !$result
statement.
Use empty()
to prevent a notice-level warning:
if (!empty($result)) {
// do something
}
Yes, both snippets are equivalent. is_null is defined as:
Returns TRUE if var is null, FALSE otherwise.
The documentation also makes it clear that is_null
throws out a warning when the variable is undefined, as does a simple boolean evaluation of $result
. If $result
is unset, is_null($result)
is true and you therefore get one warning - the same behavior as you'd with !$result
.
Since the boolean evaluation of NULL is (unsurprisingly) false, we can simply test out all interesting values:
$result is_null($result) !$result is_null($result) || !$result
(unset) true(+warn) true(+warn) true (+warn)
null true true true
false(-y) false true true
true(-ish) false false false
Note that the results of is_null
and !$result
are identical for all values that evaluate to false as well for all ones evaluating to true. Therefore, no further distinction (say, by testing 0
, ""
, etc.) is necessary.
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