Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcut for the "isset construct"?

Tags:

php

isset

I'm writing quite often this line of code:

$myParam = isset($params['myParam']) ? $params['myParam'] : 'defaultValue';

Typically, it makes the line very long for nested arrays.

Can I make it shorter?

like image 728
Martin Vseticka Avatar asked Nov 21 '11 18:11

Martin Vseticka


1 Answers

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

$myParam = getOr($params['myParam'], 'defaultValue');

Be sure to pass the variable by reference though, otherwise the code will produce a E_NOTICE. Also the use of if/else instead of a ternary operator is intentional here, so the zval can be shared if you are using PHP < 5.4.0RC1.

like image 198
NikiC Avatar answered Oct 13 '22 18:10

NikiC