PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the empty()
function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
From manual: Returns FALSE if var has a non-empty and non-zero value. The following things are considered to be empty: "" (an empty string) 0 (0 as an integer)
You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead. empty() is the equivalent of !
We can use empty() function to check whether a string is empty or not. The function is used to check whether the string is empty or not. It will return true if the string is empty. Parameter: Variable to check whether it is empty or not.
This didn't work for me.
if (empty($variable) && '0' != $variable) { // Do something }
I used instead:
if (empty($variable) && strlen($variable) == 0) { // Do something }
I seldom use empty()
for the reason you describe. It confuses legitimate values with emptiness. Maybe it's because I do a lot of work in SQL, but I prefer to use NULL
to denote the absence of a value.
PHP has a function is_null()
which tests for a variable or expression being NULL
.
$foo = 0; if (is_null($foo)) print "integer 0 is null!\n"; else print "integer 0 foo is not null!\n"; $foo = "0"; if (is_null($foo)) print "string '0' is null!\n"; else print "string '0' is not null!\n"; $foo = ""; if (is_null($foo)) print "string '' is null!\n"; else print "string '' is not null!\n"; $foo = false; if (is_null($foo)) print "boolean false is null!\n"; else print "boolean false is not null!\n";
You can also use the exactly equals operator ===
to do a similar test:
if ($foo === null) print "foo is null!\n";
This is true if $foo
is NULL
, but not if it's false
, zero, ""
, etc.
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