How to abbreviate the ternary operator in php

怪我咯
Release: 2023-03-10 21:46:01
Original
3156 people have browsed it

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;;
}
Copy after login

Use the following code instead:

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

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;;
Copy after login

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;;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!