Examples of using PHP ternary/three mesh operators

Source: Internet
Author: User

The ternary operator's functionality is consistent with the "if....else" process statement, which is written in a single line, with a streamlined code and high execution efficiency. Using the ternary operator appropriately in a PHP program can make the script more concise and efficient. The syntax for the code is as follows:

(EXPR1)? (EXPR2):(EXPR3); Expression 1-expression 2: Expression 3

Explanation: If the condition "EXPR1" is established, the statement "EXPR2" is executed, otherwise "EXPR3" is executed.

The code is as follows Copy Code

? Php
$a = 10; $b = 20;
$c = $a > $b? ($a-$b):($a + $b);
Note: If variable A is greater than variable B, the following question is executed, otherwise it is executed: after the colon
Echo $c;
?>

An expression can be a function, an array, and so on.

In fact, the ternary operator can be extended to use, when the set of conditions or not set up, execute the statement can be more than one sentence, the following format:

The code is as follows Copy Code

(EXPR1)? (EXPR2). (EXPR3): (EXPR4). (EXPR5);

We see very clearly that multiple execution statements can use the string operator notation ("." , each execution statement is surrounded by small brackets to indicate that it is an independent and complete execution statement. This extends its functionality to a more approximate "if...else" process statement.
The ternary operator can also be used in nested nesting. For example, A is larger than B: if a is less than C, then x=c-a otherwise x=a-c; otherwise a is less than B: if B is less than C, then x=c-b otherwise x=b-c:

The code is as follows Copy Code

$a > $b? $x = ($a < $c? $c-$a: $a-$c): $x = ($b < $c? $c-$b: $b-$c);

The ternary operators used in nesting are not very readable, and future maintenance of the code is likely to be problematic, so let's do it directly using if else if.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.