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"??
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:
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
empty should mean empty .. whatever deceze says.
When I do
I expect that
var_dump(empty($var));
will return false.if you are checking things in an array you always have to do
isset($var)
first.use only
($_POST['input_field_name'])!=0
instead of!($_POST['input_field_name'])==0
then 0 is not treated as empty.From manual: Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
More: http://php.net/manual/en/function.empty.php
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements,
0
(or the string'0'
which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.using
empty()
first and thenstrlen()
is your best best if you need this as well, as:It 's working for me!