views:

246

answers:

6

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"??

+8  A: 

http://php.net/empty

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Try isset instead.

deceze
mysqllearner
Tried isset(), same result
mysqllearner
@mysql For this case you might as well use `!empty($var)`, but note that that's not the same as what you wrote in the question. What to use depends entirely on what values you want to regard as `true`. Just compare the differences between `isset` and `empty` and choose the right combination for the right situation.
deceze
Felix Kling
A: 

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

From PHP Manual

In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.

codaddict
A: 

empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()

soulmerge
+1  A: 

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)
  • "0" (0 as a string) NULL
  • FALSE array() (an empty array) var
  • $var; (a variable declared, but without a value in a class)

More: http://php.net/manual/en/function.empty.php

Adam Kiss
+8  A: 

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 = "";        | 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

Cassy
+1  A: 

From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.

Elzo Valugi