Php ternary operator instance details, operator instance details

Source: Internet
Author: User

Php ternary operator instance details, operator instance details

The functions of the ternary operator are the same as those of the "if... else" flow statement. It is written in one line, and the code is refined and the execution efficiency is high. The proper use of ternary operators in PHP programs makes scripts more concise and efficient. The code syntax is as follows:

(Expr1 )? (Expr2) :( expr3); // expression 1? Expression 2: expression 3

Explanation: if the condition "expr1" is true, execute the statement "expr2"; otherwise, execute "expr3 ".

<? PHP $ a = 10; $ B = 20; $ c = $ a> $ B? ($ A-$ B) :( $ a + $ B); // Note: If variable a is greater than variable B, execute the following question mark; otherwise, execute: echo $ c;?>

EXPRESSIONS Can Be functions, arrays, and so on.

In fact, the ternary operators can be extended and used. When the set conditions are true or not true, more than one statement can be executed, in the following format:

(Expr1 )? (Expr2). (expr3): (expr4). (expr5 );

We can see that multiple execution statements can use the string operator number (". ), and each execution statement is enclosed by small angle brackets to indicate that it is an independent and complete execution statement. In this way, its function is closer to the "if... else" flow statement.

The ternary operators can also be nested. For example, when a is greater 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:

$ A> $ B? $ X = ($ a <$ c? $ C-$ a: $ a-$ c): $ x = ($ B <$ c? $ C-$ B: $ B-$ c );

The ternary operators used for nesting are not very readable, and there may be problems with code maintenance in the future. So in this case, we should directly use if else if for implementation.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.