Skip to content
Advertisement

PHP variable “default value”

I want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice.

You can write a function that does this

function get(&$var, $default){
    if(isset($var)) return $var;
    return $default;
}

echo get($foo, "barn");
$foobar = "foobar";
echo get($foobar, "ERROR");

Example in action

Is there a way to do this without defining this function in every file?

Advertisement

Answer

From PHP 7, you can now use the null coalescing operator :

$var ?? $default

that does exactly like your function

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement