Recipe 5.2. Establishing a Default Value

5.2.1. Problem

You want to assign a default value to a variable that doesn't already have a value. It often happens that you want a hardcoded default value for a variable that can be overridden from form input or through an environment variable.

5.2.2. Solution

Use isset( ) to assign a default to a variable that may already have a value:

if (! isset($cars)) { $cars = $default_cars; }

Use the ternary (a ? b : c) operator to give a new variable a (possibly default) value:

$cars = isset($_REQUEST['cars']) ? $_REQUEST['cars'] : $default_cars;

5.2.3. Discussion

Using isset( ) is essential when assigning default values. Without it, the nondefault value can't be 0 or anything else that evaluates to false. Consider this assignment:

$cars = $_REQUEST['cars'] ? $_REQUEST['cars'] : $default_cars;

If $_REQUEST['cars'] is 0, $cars is set to $default_cars even though 0 may be a valid value for $cars.

An alternative syntax for checking arrays is the array_key_exists( ) function:

$cars = array_key_exists('cars', $_REQUEST) ? $_REQUEST['cars'] : $default_cars;

The one difference between isset( ) and array_key_exists( ) is that when a key exists but its value is null, then array_key_exists( ) returns true, while isset( ) returns false:

$vehicles = array('cars' => null); array_key_exists('cars', $vehicles); // true isset($vehicles['cars']);            // false

You can use an array of defaults to set multiple default values easily. The keys in the defaults array are variable names, and the values in the array are the defaults for each variable:

$defaults = array('emperors'  => array('Rudolf II','Caligula'),                   'vegetable' => 'celery',                   'acres'     => 15); foreach ($defaults as $k => $v) {     if (! isset($GLOBALS[$k])) { $GLOBALS[$k] = $v; } }

Because the variables are set in the global namespace, the previous code doesn't work for setting function-private defaults. To do that, use variable variables:

foreach ($defaults as $k => $v) {     if (! isset($$k)) { $$k = $v; } }

In this example, the first time through the loop, $k is emperors, so $$k is $emperors.

5.2.4. See Also

Documentation on isset( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: