Introduction to the concatenation of PHP ternary operators

Source: Internet
Author: User
Introduction to the concatenation of PHP ternary operators. For more information, see. Let's first look at a three-element formula:

Copy codeThe code is as follows:
$ A = 1; $ B = 2; $ c = 3; $ d = 4;
Echo $ a <$ B? 'Xx': $ a <$ c? 'Yy': $ a <$ d? 'Zs': 'Oo ';
?>

Generally, according to the rules of other languages (such as C or Java), the calculation logic of the above code is:

Copy codeThe code is as follows:
$ A <$ B => true => 'XX' => end

The final result is 'XX', and subsequent operations will be ignored.
However, it is surprising that the final result obtained by the above code in php operations is 'zz '... I will clean it up. what is the situation? isn't it so boring...
Old rules, I had to ask for Google sauce, and I was told that the three-element calculation of php was actually a combination of the left... so I was suddenly enlightened.
I added two parentheses to the above code:

Copy codeThe code is as follows:
$ A = 1; $ B = 2; $ c = 3; $ d = 4;
Echo ($ a <$ B? 'Xx': $ a <$ c )? 'Yy': $ a <$ d )? 'Zs': 'Oo ';
?>

It's clear. this is the php computing logic:

Copy codeThe code is as follows:
$ A <$ B => true => 'XX' => true => 'yy' => true => 'zz '=> end

Two types of conversion are involved, namely, 'XX' => true and 'XX' => true.
I don't know if this process is a pain point. it is really hard to understand...
Finally, return to the above code and change it to a right combination like C:

Copy codeThe code is as follows:
$ A = 1; $ B = 2; $ c = 3; $ d = 4;
Echo $ a <$ B? 'Xx' :( $ a <$ c? 'Yy' :( $ a <$ d? 'Zs': 'Oo '));
// Just change the brackets to the lower position. the brackets in php are not allowed.
?>

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.