Home >Backend Development >PHP Tutorial >How to abbreviate the ternary operator in php
Today I discovered a small usage of PHPternary operation operator. This gives my dry brain a little fun!
PHP TernaryOperator is a concise main usage when assigning parameters. A main usage: PHP ternary operator allows you to describe the judgment code in one line of code, thereby replacing something like The following code:
<?phpif (isset($value)) { $output = $value; } else { $output = 'No value set.'; }
Use the following code instead:
<?php$output = isset($value) ? $value : 'No value set.';
The second code example is a very concise usage, which is very practical in many situations (not all) Usage. There is a lot of debate about whether you should use the ternary operator; let me say, it is a tool, just like any other tool, it is just used correctly or not.
The commonly used syntax is (expression)? value if truthy: value if falsy. This expression can be a variable, test whether this variable is true or false:
<?php$output = $value ? $value : 'No value set.';
The problem is: The above example is very It’s commonly used but also a bit annoying to repeat: writing $value twice feels like a mistake.
Fortunately, today I found a more concise usage introduced inPHP 5.3
The syntax of the ternary operator. You can learn it from the manual, but here we can make the above example more concise:
<?php$output = $value ?: 'No value set.';
This one looks familiar, because it is very similar to other shorthand operators ; When concise code, this way will look clearer, we
shouldwrite like this,
(and this feature allows us to use this operator in many situationsThe above is the detailed content of How to abbreviate the ternary operator in php. For more information, please follow other related articles on the PHP Chinese website!