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?
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?
check this out: http://www.php.net/manual/en/types.comparisons.php
that will answer your question in depth
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.
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)
.
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)