In PHP I find myself writing code like this frequently:
$a = isset($the->very->long->variable[$index]) ? $the->very->long->variable[$index] : null;
Is there a simpler way to do this? Preferably one that doesn't require me to write $the->very->long->variable[$index]
twice.
Or to assign default to VARIABLE at the same time: FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.
This will work: x = $(if [ 2 = 2 ]; then echo equal; else echo "not equal; fi) . See gnu.org/software/bash/manual/bash.html#Conditional-Constructs . Note that case matters -- If and if are not the same. if you want to echo it in one line.
Description. The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.
An update, because PHP 7 is now out and is a game-changer on this point ; the previous answers are about PHP 5.
PHP 7 solves this issue. Because you are true at saying that it is frequent to write this in PHP, and that's absolutely not elegant.
In PHP 7 comes the Null Coalesce Operator (RFC), which is a perfect shorthand for the isset ternary condition.
Its goal is to replace this type of condition:
$var = isset($dict['optional']) ? $dict['optional'] : 'fallback';
By that:
$var = $dict['optional'] ?? 'fallback';
Even better, the null coalesce operators are chainable:
$x = null; # $y = null; (undefined) $z = 'fallback'; # PHP 7 echo $x ?? $y ?? $z #=> "fallback" # PHP 5 echo isset($x) ? $x : (isset($y) ? $y : $z)
The null coalesce operator acts exactly like isset()
: the subject variable's value is taken if:
Just a note for PHP beginners: if you use the ternary condition but you know that the subject variable is necessarily defined (but you want a fallback for falsy values), there's the Elvis operator:
$var = $dict['optional'] ?: 'fallback';
With the Elvis operator, if $dict['optional']
is an invalid offset or $dict
is undefined, you'll get a E_NOTICE
warning (PHP 5 & 7). That's why, in PHP 5, people are using the hideous isset a ? a : b form when they're not sure about the input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With