views:

76

answers:

3

Which is better to use when I use _GET['something here'] for a variable to check if it is empty or not

if (isset($_GET['url']) != '') {
    //do stuff with it
}

OR

if (isset($_GET['url']) != NULL) {
    //do stuff with it
}

'' or null or something else?

Please don't call this over optimizing or micro optimizing, I am simply looking for best practices, thank you

+6  A: 

Use empty() - it actually first test of the variable exists before testing whether something is in it.

[Edit: isset() returns only TRUE or FALSE, so both of the statements above work equally well]

dmitrig01
+4  A: 

You should do the following to be sure that the value both exists and isn't empty

if(isset($_POST[myField]) && $_POST[myField] != "") {
Do my PHP code
}
Am
That is what I used in the past but then I saw people doing it like if(isset($something)) and I ran it and it worked so I thought it was good, guess i should do the 2 checks
jasondavis
+2  A: 

PHP can be a little painful when debugging blank/missing/empty value checks. You can use empty() or isset(), but remember the cases where empty returns true. It's highly liberal with what it considers empty.

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)

isset is more conservative in that it only checks for variable's existence and a NULL value. From the documentation:

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Anurag