Home >Backend Development >PHP Tutorial >How to abbreviate the ternary operator in php

How to abbreviate the ternary operator in php

怪我咯
怪我咯Original
2017-06-20 14:08:013188browse

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 = &#39;No value set.&#39;;
}

Use the following code instead:

<?php$output = isset($value) ? $value : &#39;No value set.&#39;;

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 : &#39;No value set.&#39;;

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 ?: &#39;No value set.&#39;;

This one looks familiar, because it is very similar to other shorthand operators ; When concise code, this way will look clearer, we

should

write like this,

(and this feature allows us to use this operator in many situations

The 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn