Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP short statement to make variable fallback to default [duplicate]

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.

like image 327
Alfred Huang Avatar asked Oct 24 '25 11:10

Alfred Huang


1 Answers

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

like image 170
Alfred Huang Avatar answered Oct 27 '25 02:10

Alfred Huang