Categories
PHP

Testing, setting, and unsetting variables

Before attempting to use variables that come from an external source such as a user-submitted form, you must check whether those variables are defined or not. isset() function is one of the most common tests to check whether a variable has been defined.

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:

//Syntax
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:

<?php
$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():

//Syntax
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";

The following table shows 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:

State of the variable $varisset($var)empty($var)(bool)$var
$var = null;falsetruefalse
$var = 0;truetruefalse
$var = truetruefalsetrue
$var = falsetruetruefalse
$var = “0”;truetruefalse
$var = “”;truetruefalse
$var = “foo”;truefalsetrue
$var = array( );truetruefalse
unset $var;falsetruefalse
Expression Values

You can also test a variable for a specific data type, see, “Determine a variable data type” tutorial.


Data types in PHP:

  1. Data Types
  2. Determine Variable Data Type
  3. Type Conversion: Convert variable data type
  4. Type Declaration
  5. Strict Typing Mode
  6. Testing, setting, and unsetting variables