Introduction to the concatenation of PHP ternary Operators

Source: Internet
Author: User

Let's first look at a three-element formula:

Copy codeThe Code is as follows:
<? Php
$ 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:
<? Php
$ 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:
<? Php
$ 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.