Evaluating a variable, whether it is generated by a script or input by a user, turns out to be somewhat more complicated than one might suspect. The focus here will be on determining whether the variable contains something; if it does, then additional tests will normally be necessary to determine whether it contains something meaningful.
Among the techniques that might be considered are the following:
1. if (!$var) 2. if (empty($var)) 3. if ($var=='') 4. if ($var==='') 5. if (isset($var)) 6. if strlen($var)==0 7. if (is_string($var))
Among the possible values that a variable might possess are the following:
1. a string value, 'something' 2. a numerical value, 12345 3. the empty value, '' 4. the integers 1 or 0 5. the boolean constants TRUE or FALSE 6. NULL
Or a variable might be unset.
User input in response to a form can exist only as a string value. If the user inputs a number, it will be treated as a string for evaluation.
An array or a text variable coming from a form via checkbox or radio will be unset if the user doesn’t check anything. But no text variable coming from a form via input can be unset. If the user doesn’t input a value, the variable will be empty (='').
Thus, TRUE/FALSE and NULL are impossible values for form-generated variables, as are the integers (as opposed to the strings) 1 and 0.
A variable generated by a script might have any of the possible values. A variable that is conditionally generated might be unset.
This table shows how each of these possible values is evaluated by each technique (note that “unset” is not actually a value):
|typical use→||variables usually with forms||variables usually with scripts|
|↓test | value→||something||12345||''||0||FALSE||NULL||[unset]|
This table demonstrates somewhat surprising results:
What conclusions can we draw?
Analyzing exactly why a test like if (!$var) returns true when $var=FALSE gets us into metaphysics: can “nothing” nevertheless be something by virtue of being the thing “nothing”? To put it another way, if 0 and FALSE and NULL are in fact some sort of values, how can the variables containing them be considered false or empty? Apparently, in some cases they are recognized as not being empty:
Once again, most of these problems can be avoided by using strict comparisons, with careful attention to types so that no mixing takes place.
Information from The PHP Manual on type comparison can be found here.
Contributors to this note include the following:
the PHundamentals team: Jeff Siegel and Mike Southwell
Free API and developer tools console for PageSpeed optimization.