Should I use null to see if a variable is empty in PHP?
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 开发者_StackOverflow社区this over optimizing or micro optimizing, I am simply looking for best practices, thank you
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]
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
}
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.
精彩评论