In the PHP view, there is an operator for this (starting with 5.3) that would compress your example:
$myFruit = $_REQUEST['myfruit'] ?: "apple";
However , I say βviewβ because it only checks the first operand for false and will not suppress notifications if it is not set. Therefore, if (as in your example) this may not be indicated, your source code is best.
A function similar to the .get dictionary is trivial:
function dget($dict, $key, $default) { return isset($dict[$key]) ? $dict[$key] : $default; }
For clarity, I use your original code anyway.
Edit: the implementation of userland # 2 ifsetor () in http://wiki.php.net/rfc/ifsetor is slightly ahead of the function above and works with non-arrays too, but it has the same caveat that the default expression will always be evaluated, even if not in use:
function ifsetor(&$variable, $default = null) { if (isset($variable)) { $tmp = $variable; } else { $tmp = $default; } return $tmp; }
Long ears
source share