Home  >  Article  >  Backend Development  >  A more concise ternary operator in php ?:

A more concise ternary operator in php ?:

WBOY
WBOYOriginal
2016-08-08 09:29:28883browse

Original addressEven shorter ternary operators in PHP using ?:

Today I discovered a small usage of PHP ternary operator. This gave my dry brain a little fun!

PHP ternary operator is a pair of parameters A concise main usage when assigning values. A main usage: PHP ternary operator allows you to describe the judgment code in one line of code, thereby replacing code similar to the following:

<code><span><?php</span><span>if</span> (<span>isset</span>(<span>$value</span>)) {
    <span>$output</span> = <span>$value</span>;
} <span>else</span> {
    <span>$output</span> = <span>'No value set.'</span>;
}</code>

Use the following code instead:

<code><span><?php</span><span>$output</span> = <span>isset</span>(<span>$value</span>) ? <span>$value</span> : <span>'No value set.'</span>;</code>

Chapter The two code examples are very concise usage, and in many situations (not all), this is a very practical usage. There is a lot of debate about whether you should use the ternary operator; let me say, this is a tool, Like other tools, it just needs to be used correctly.

The commonly used syntax is (expression) ? value if truthy : value if falsy. This expression can be a variable, test whether the variable is true or false:

<code><span><?php</span><span>$output</span> = <span>$value</span> ? <span>$value</span> : <span>'No value set.'</span>;</code>

Question Yes: The above example is very common and annoyingly repetitive: writing $value twice feels like a mistake.

Fortunately, today I found a more concise way to use ternary introduced in PHP 5.3 Operator syntax. You can learn it from the manual, but here we can make the above example more concise:

<code><span><?php</span><span>$output</span> = <span>$value</span> ?: <span>'No value set.'</span>;</code>

This one looks familiar, because it is very similar to other shorthand operators:

<code><span><?php</span><span>$value</span> = <span>$value</span> . <span>$other_value</span>;</code>

Convert to :

<code><span><?php</span><span>$value</span> .= <span>$other_value</span>;</code>

For the sake of simplicity, just because we can abbreviate it this way doesn’t mean we should write it this way. However, when we write concise code, this way it will look clearer and we should write it this way, (And this feature allows us to DRY up the ternary operator in many cases]

The above introduces the more concise ternary operator ?: in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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