Deep analysis of PHP operator precedence

Source: Internet
Author: User
Tags php operator

Zhou 51 friend a piece of code to ask me, said he could not understand this code, think that this code has a problem, the code is similar:

The code is as follows Copy Code

$array 1 = Array (1, 2);
$array 2 = Array (3, 4);

$result = Empty ($array 1) = = 3? $array 1: $array 2;

I think it should be the problem of operator precedence.
Logically, the problem with the precedence of these operators is that they should not appear in the project code, only to allow it in the interview question, the programmer should use parentheses in the writing code to avoid this uncertainty problem. The code in the project should be the kind of thing we know when we see the results, not what we need to do to get the results. The results of this priority code are sometimes not what we believe, and look at the following example:

The code is as follows Copy Code

<?php
if ($a = && $b = 200) {
Var_dump ($a, $b);
}

The above code you might think is:

The code is as follows Copy Code
<?php
if ($a = (&& $b) = 200) {
Var_dump ($a, $b);
}

But this is not the case, the actual result is:

The code is as follows Copy Code
<?php
if ($a = (&& $b = 200)) {
Var_dump ($a, $b);
}

And why is that? That's because PHP doesn't fully follow the priority definition, as explained in the PHP manual

Note:although = has a lower precedence than most other operators, PHP would still allow the expressions to the similar Ng:if (! $a = foo ()), in which case the return value of Foo () was put into $a.

Code:

Code 1:

The code is as follows Copy Code

<?php
$x =true;
$y =false;
$z = $y or $x;?>
Code 2:
<?php
$x =true;
$y =false;
$z = $y | | $x;
?>

This code should not appear in the actual project, and should be replaced with the following code:

  code is as follows copy code

$z = ($y OR $x );

$z = ($y | | $x);

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.