Testing, setting, and unsetting variables
During the running of a PHP script, a variable may be in an unset state or may not yet be defined. PHP provides the isset( ) function and the empty( ) language construct to test the state of variables:
boolean isset(mixed var) boolean empty(mixed var)
isset( ) tests if a variable has been set with a non-null value, while empty( ) tests if a variable has a value. The two are different, as shown by the following code:
$var = "test"; // prints: "Variable is Set" if (isset($var)) echo "Variable is Set"; // does not print if (empty($var)) echo "Variable is Empty";
A variable can be explicitly destroyed using unset( ):
unset(mixed var [, mixed var [, ...]])
After the call to unset in the following example, $var is no longer defined:
$var = "foo"; // Later in the script unset($var); // Does not print if (isset($var)) echo "Variable is Set";
Another way to test that a variable is empty is to force it to the Boolean type using the (bool) cast operator discussed earlier. The example interprets the $var variable as type Boolean, which is equivalent to testing for !empty($var):
$var = "foo"; // Both lines are printed if ((bool)$var) echo "Variable is not Empty"; if (!empty($var)) echo "Variable is not Empty";
Table 2-2 show the return values for isset($var), empty($var), and (bool)$var when the variable $var is tested. Some of the results may be unexpected: when $var is set to "0", empty( ) returns true.
Table 2-2. Expression values
| State of the variable $var | isset($var) | empty($var) | (bool)$var |
|---|---|---|---|
| $var = null; | false | true | false |
| $var = 0; | true | true | false |
| $var = true | true | false | true |
| $var = false | true | true | false |
| $var = "0"; | true | true | false |
| $var = ""; | true | true | false |
| $var = "foo"; | true | false | true |
| $var = array( ); | true | true | false |
| unset $var; | false | true | false |