Code will explain more:
$var = 0; if (!empty($var)){ echo "Its not empty"; } else { echo "Its empty"; }
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
The following things are considered to be empty: "" (an empty string) 0 (0 as an integer)
PHP empty() FunctionThe 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.
NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.
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.
http://php.net/empty
The following things are considered to be empty:
- "" (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)
Note that this is exactly the same list as for a coercion to Boolean false
. empty
is simply !isset($var) || !$var
. Try isset
instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x) ----------------+-------- $x = ""; | true $x = null | true var $x; | true $x is undefined | true $x = array(); | true $x = false; | true $x = true; | false $x = 1; | false $x = 42; | false $x = 0; | true $x = -1; | false $x = "1"; | false $x = "0"; | true $x = "-1"; | false $x = "php"; | false $x = "true"; | false $x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
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