Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, "bar\n");
$foobar = "foobar";
echo get($foobar, "ERROR");

Example in action

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

like image 283
dtech Avatar asked Jun 22 '12 17:06

dtech


1 Answers

You can define it in one script and then require_once that script in your other scripts

You could also just use the ternary operator:

$myVar = isset($var)?$var:$default;
like image 112
ametren Avatar answered Oct 12 '22 23:10

ametren