In Python one can do:
foo = {}
assert foo.get(\'bar\', \'baz\') == \'baz\'
In PHP one can go for a trinary operator as in:<
PHP 5.3 has a shortcut version of the ternary operator:
$x = $foo ?: 'defaultvaluehere';
which is basically
if (isset($foo)) {
$x = $foo;
else {
$x = 'defaultvaluehere';
}
Otherwise, no, there's no shorter method.
There was a solution proposed by "Marc B" to use ternary shortcut $x = $foo ?: 'defaultvaluehere';
but it still gives notices. Probably it's a mistyping, maybe he meant ?? or it were written before PHP 7 release.
According to Ternary description:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
But it doesn't use isset
inside and produces notices.
To avoid notices better to use Null Coalescing Operator ??
which uses isset
inside it. Available in PHP 7.
The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise. In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys.
Example #5 Assigning a default value
<?php
// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';
// The above is identical to this if/else statement
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else {
$action = 'default';
}
?>