Reputation: 31487
What is the difference between these four PHP statements?
if (isset($data)) {
if (!empty($data)) {
if ($data != '') {
if ($data) {
Do they all do the same?
Upvotes: 12
Views: 30532
Reputation: 20010
Check PHP manual out: http://www.php.net/manual/en/types.comparisons.php
Expression gettype() empty() is_null() isset() if($x) $x = ""; string TRUE FALSE TRUE FALSE $x = null; NULL TRUE TRUE FALSE FALSE var $x; NULL TRUE TRUE FALSE FALSE $x undefined NULL TRUE TRUE FALSE FALSE $x = array(); array TRUE FALSE TRUE FALSE $x = false; boolean TRUE FALSE TRUE FALSE $x = true; boolean FALSE FALSE TRUE TRUE $x = 1; integer FALSE FALSE TRUE TRUE $x = 42; integer FALSE FALSE TRUE TRUE $x = 0; integer TRUE FALSE TRUE FALSE $x = -1; integer FALSE FALSE TRUE TRUE $x = "1"; string FALSE FALSE TRUE TRUE $x = "0"; string TRUE FALSE TRUE FALSE $x = "-1"; string FALSE FALSE TRUE TRUE $x = "php"; string FALSE FALSE TRUE TRUE $x = "true"; string FALSE FALSE TRUE TRUE $x = "false"; string FALSE FALSE TRUE TRUE
As you can see, if(!empty($x))
is equal to if($x)
and if(!is_null($x))
is equal to if(isset($x))
. As far as if $data != ''
goes, it is TRUE
if $data
is not NULL
, ''
, FALSE
or 0
(loose comparison).
Upvotes: 25
Reputation: 186692
They aren't the same.
true if the variable is set. the variable can be set to blank and this would be true.
true if the variable is set and does not equal empty string, 0, '0', NULL, FALSE, blank array. it is clearly not the same as isset
.
if the variable does not equal an empty string, if the variable isnt set its an empty string.
if the variable coerces to true, if the variable isnt set it will coerce to false.
Upvotes: 4
Reputation: 9917
if (isset($data)) - Determines if a variable is set (has not bet 'unset()'
and is not NULL
.
if (!empty($data)) - Is a type agnostic check for empty if $data was '', 0, false, or NULL it would return true.
if ($data != '') { this is a string type safe of checking whether $data is not equal to an empty string
if ($data) { this is a looking for true or false (aka: 0 or 1)
Upvotes: 0
Reputation: 152284
if (isset($data)) {
Variable is just set - before that line we declared new variable with name 'data', i.e. $data = 'abc';
if (!empty($data)) {
Variable is filled with data. It cannot have empty array because then $data
has array type but still has no data, i.e. $data = array(1);
Cannot be null, empty string, empty array, empty object, 0, etc.
if ($data != '') {
Variable is not an empty string. But also cannot be empty value (examples above).
If we want to compare types, use !==
or ===
.
if ($data) {
Variable is filled out with any data. Same thing as !empty($data)
.
Upvotes: 10