Today I discovered a small usage of the PHP ternary operator. This gave my dry brain a little fun!
PHP ternary operator is a concise main usage when assigning values to parameters. . One major usage: The PHP ternary operator allows you to describe the decision code in one line of code, thereby replacing code similar to the following:
Copy after login
Use the following code to replace:
Copy after login
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:
Copy after login
The problem is: the above example is very common and annoyingly repetitive: writing $value twice feels like a mistake.
Fortunately, I found out today thatPHP 5.3
introduced a more concise syntax using the ternary operator. You can learn it from the manual, but here how do we make the above example more concise:
Copy after login
Look at this It looks familiar, because it is very similar to other abbreviation operators:
Copy after login
converts to:
Copy after login
For the sake of simplicity, this means that we can abbreviate this way but it does not mean that we canshouldbe written like this. However, when we write concise code, this way will look clearer, weshouldbe written like this,(and this feature allows us to Even shorter ternary operators in PHP using ?:
Today I discovered a small usage of the PHP ternary operator. This gave my dry brain a little fun! PHP ternary operator is a concise way to assign values to parameters. Main usage. 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:Copy after login
Copy after login
Copy after login
PHP 5.3
introduced a more concise syntax using the ternary operator. You can learn it from the manual, but here how do we make the above example more concise:Copy after login
Copy after login
converts to:
Copy after login
should
be written like this. However, when we write concise code, this way will look clearer, weshould
be written like this,(and this feature allows us Use this operator in many cases[this feature allows us to DRY up the ternary operator in many cases])
The above is the detailed content of PHP tips to make using the ternary operator easier. For more information, please follow other related articles on the PHP Chinese website!