Today I discovered a small usage of PHPternary operationoperator. This gives my dry brain a little fun!
PHP TernaryOperatoris 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:
Copy after login
Use the following code instead:
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. Thisexpressioncan be avariable, test whether this variable is true or false:
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:
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
shouldwrite 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!