As we know, if we are using javascript or python, we can use the below statement to get a variable, or its default.
// javascript
alert(a || 'default');
# python
print(a or 'default');
While in php, we may have to call the below:
echo $a ? $a : 'default';
And if the $a is a very long statement, the case is even worse:
echo (
we_made_many_calculation_here_and_this_is_the_result() ?
we_made_many_calculation_here_and_this_is_the_result() :
'default'
);
or
var $result = we_made_many_calculation_here_and_this_is_the_result();
echo $result ? $result : 'default';
any of the above, I think it is not neat.
And I'm blind to find any answer, to find a statement or built-in function to simplifies the work. But after trying to search many ways, I can't find the answer.
So please help.
Relating to this issue: http://php.net/manual/en/language.operators.logical.php#115208
So, see the documentation of the ternary operator, it is possible to use:
echo $a ?: 'defaults for a';
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
See: http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
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