views:

262

answers:

5

Is there any advantage to writing a PHP conditional like this:

if ($variable != NULL) {

versus

if (!empty($variable)) {

versus

if ($variable) {

Aren't they all same thing? It seems like the last is always the simplest if you are just trying to tell whether the variable exists or not. Thanks for helping me understand the difference here. I missed the first day of PHP 101.

+4  A: 

Check out this table to get the skinny on PHP comparison operators. There's a number of subtle differences between false, 0, "", NULL and variables that are simply undefined.

Sean McSomething
I never knew that table existed. Thanks!
sirlancelot
+1  A: 

I agree with Sean but I'll outline what each does in plain English:

if ($variable != NULL) {

$variable will be NULL if it hasn't been set. This is practically the same as isset and the same as the variable being undefined.

if (!empty($variable)) {

Generally, this checks whether $variable as a string ((string) $variable) has a strlen of 0. However true will make it return false, as will integers that aren't 0 and empty arrays. For some reason (which I believe to be wrong) $variable = '0'; will return true.

if ($variable) {

This true/false check acts like (boolean) $variable - basically whether the variable returns true when converted to a boolean.

One way to think about it is that it acts the same as empty, except returns the opposite value.

For more information on what I mean by (boolean) $variable (type casting/juggling) see this manual page.

(PHP devs: this is mainly by memory, if I'm wrong here please correct me!)

Ross
NULL isn't the same as undefined.
JW
+1  A: 

Related Question: http://stackoverflow.com/questions/413929/weak-typing-in-php-why-use-isset-at-all

Basically, they are not the same when dealing with empty values, null values, zero, and boolean values.

sirlancelot
+1  A: 

When running in strict error mode (E_STRICT), the clauses

if ($variable) {}

and

if ($variable != null) {}

would throw Notices, when these variables are not initialized.

Notice: Undefined variable: variable

These notices are a indicators of flaws in the code, since the use of uninitialized is a possible security vulnerability. (Keyword: register_globals).

My favorite for checking the existence of a variable is

if (isset($variable)) {}

This checks, if the variable has been used before (read: initialized with a value != null).

Cassy