views:

391

answers:

4

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?

+6  A: 

check this out: http://www.php.net/manual/en/types.comparisons.php

that will answer your question in depth

Janek
+3  A: 

They aren't the same.

  1. true if the variable is set. the variable can be set to blank and this would be true.

  2. 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.

  3. if the variable does not equal an empty string, if the variable isnt set its an empty string.

  4. if the variable coerces to true, if the variable isnt set it will coerce to false.

meder
+2  A: 
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).

hsz
+1  A: 

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)

Skawful
`if ($data) { this is a looking for true or false (aka: 0 or 1)` <- not quite correct. This will be true if `$data` contains something that doesn't resolve to false (essentially the same things as `!empty($data)`)
Blair McMillan