which is better?
if (!empty($val)) { // do something }
and
if ($val) { // do something }
when i test it with PHP 5, all cases produce the same results. what about PHP 4, or have any idea which way is better?
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.
"isset() checks if a variable has a value including (False, 0 or empty string), but not NULL. Returns TRUE if var exists; FALSE otherwise. On the other hand the empty() function checks if the variable has an empty value empty string, 0, NULL or False. Returns FALSE if var has a non-empty and non-zero value."
An empty array evaluates to FALSE , any other array to TRUE (Demo):
NULL and empty - PHP TutorialNull is a fancy term for nothing, for not having a value. It's not zero, it's not an empty string, it's the actual lack of a value. I mean, if we can set a value into a variable, then we also have to have some way to talk about the fact that variable might not have a value at all.
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 !isset($var) || $var == false
. It returns true if the variable is:
""
(an empty string)0
(0 as an integer)0.0
(0 as a float)"0"
(0 as a string)NULL
FALSE
array()
(an empty array)var $var;
(a variable declared, but without a value in a class)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