PHP: Assign a default value to a variable

PHP E_ALL causes a warning to be thrown if you read an unitialized value from an array. For example if you did $debug = $_GET['debug']; but debug is not present in $_GET.

This function will conditionally assign a value to a variable that will not cause a warning to be thrown. It also has the added benefit of having a default option that you can specify.

function var_set(&$value, $default = null) {
    if (isset($value)) {
        return $value;
    } else {
        return $default;
    }
}

This allows us to safely assign a variable from the superglobals.

# Default of null if not in array
$debug = var_set($_GET['debug']);

# Specific default of 99
$level = var_set($_GET['level'],99);

Update: PHP 7+ has null coalesce built in which is better than this. $level = $_GET['level'] ?? 99

Leave A Reply
All content licensed under the Creative Commons License