I was wondering what's the difference the two cases below, and which one is recommended?
$val = 0; if (!$val) { //True } if (empty($val) { //It's also True }
The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.
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.
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. The following values evaluates to empty: 0.
Have a look at the PHP type comparison table.
If you check the table, you'll notice that for all cases, empty($x)
is the same as !$x
. So it comes down to handling uninitialised variables. !$x
creates an E_NOTICE
, whereas empty($x)
does not.
If you use empty and the variable was never set/created, no warning/error will be thrown.
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