...

View Full Version : Is thedre a reason to use EMPTY()



cseasy
09-14-2005, 04:14 PM
Guys,

Is there a reason why:


if (!empty($myId)) {
// do stuff
}

should be used instead of just:


if ($myId) {
// do stuff
}

Thanks,
C.

chump2877
09-14-2005, 04:30 PM
I think empty() let's you know if a form variable/field is actually empty, while the other method just let's you know if the variable is set or not...there are occasions when your variable will be set, but the form field is actually empty...In that case, your two pieces of code would evaluate differently...

What is it that you are trying to do with your code? Detect if a variable is empty or if a variable is not set?

cseasy
09-14-2005, 05:00 PM
Trying to detect if it's set or not, so I can render the page based on data available.

It's a directory of sorts, so I test how far in they've filtered:


if (!$categoryId && !subcategoryId && !$directoryId) {
// show category list
} else if ($categoryId && !subcategoryId && !$directoryId) {
// show subcategory list based on category
} else if ($categoryId && subcategoryId && !$directoryId) {
// show all directory entries for this subcategory
} else if ($categoryId && subcategoryId && $directoryId) {
// show directory entry
}

The variables get set based on the querystring, so it would build up as follows:

page.php
page.php?c=1
page.php?c=1&s=2
page.php?c=1&s=2&d=3

Thanks,
C.

NancyJ
09-14-2005, 05:04 PM
if you want to test if a value is set use isset() (http://uk.php.net/manual/en/function.isset.php)

chump2877
09-14-2005, 05:06 PM
Unless they're using HTML textboxes or textareas, i think you are OK to just use either:


if ($variable)
{

code;

}

or


if (isset($variable))
{

code;

}

NancyJ
09-14-2005, 05:16 PM
the top 2 lines in the handy chart show the difference between if($var) and isset($var), also has empty in there too ;)
http://www.deformedweb.co.uk/php_variable_tests.php
Basically if($var) is the same as if(!empty($var)) but not the same as isset($var)

Kid Charming
09-14-2005, 05:47 PM
Using if(!$x) is not the same as using isset() or empty(). if(!$x) tests for a negative boolean value (loosely), not the existence or contents of the variable; it's equivalent to



if($x == FALSE)


If $x is 0, NULL, or empty, if(!$x) will return true, even though $x has been set, because 0, NULL, and empty vars evaluate to FALSE in loose comparisons. You should only use if(!$x) when you know $x is a proper boolean value. Otherwise, you should use one of PHP's other variable-checking functions.

For more chart fun, here are the PHP doc's type comparison tables (http://us2.php.net/manual/en/types.comparisons.php).

cseasy
09-14-2005, 05:51 PM
Cool, thank you.

C.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum