Usage of ternary operators in php. Syntax: condition? Result 1: Result 2: the position before the question mark is the condition for judgment. if the condition is met, result 1 is displayed. if the condition is not met, result 2 is displayed. The code is as follows? PHP $ idisset ($ _ GET [id syntax: condition? Result 1: Result 2
Note: the position before the question mark is the judgment condition. if the condition is met, result 1 is displayed. if the condition is not met, result 2 is displayed.
The code is as follows: |
|
$ Id = isset ($ _ GET ['id'])? $ _ GET ['id']: false; ?> |
A piece of code replaces a lot of code. First, it uses the isset () function to check whether $ _ GET ['id'] exists. If $ _ GET ['id'] does exist, it returns its value. However, if it does not exist, the condition is false, and false is returned. The value of $ id depends on whether $ _ GET ['id'] exists. Therefore, if $ _ GET ['id'] exists, $ id = $ _ GET ['id']; otherwise, $ id = false.
Example
Use "? : "Condition statement to test user input values:
The code is as follows: |
|
$ Filename = isset ($ argv [1])? $ Argv [1]: "php: // stdin "; $ Fp = @ fopen ($ filename, 'r') or die ("Can't Open $ filename for reading "); While (! @ Feof ($ fp )){ $ Line = @ fgets ($ fp, 1024 ); Print $ line; } @ Fclose ($ fp ); ?> |
The code using the ternary operator is equivalent to the following code:
The code is as follows: |
|
If (isset ($ argv [1]) { $ Filename = $ argv [1]; } Else { $ Filename = "php: // stdin "; } ?> |
It can be seen that if the above code is written in a normal if-else structure, the amount of code will be much larger than above, but the second form is easier to understand and does not require more input. Therefore, when selecting a ternary operator, you must weigh the advantages and disadvantages.
Advantages of ternary operators
The ternary operators (? :) It greatly reduces the time for programmers to write these statements. Its syntax is as follows:
Condition? Do_if_true: do_if_false;
Ternary operators are not an essential structure, but they are a way to beautify the code. Similarly, it can replace bad if... Else code block, which can improve the readability of the code.
Similarly, you can use the PHP or computing server to assign the default value of the variable:
The code is as follows: |
|
$ Filename = $ argv [1] or $ filename = "php: // stdin "; ?> |
Why? Result 1: Result 2: the position before the question mark is the condition for judgment. if the condition is met, result 1 is displayed. if the condition is not met, result 2 is displayed. The code is as follows? PHP $ id = isset ($ _ GET ['id...