简体   繁体   English

PHP IF-ELSE 语句

[英]PHP IF-ELSE STAMENT

Code:代码:

<?php
$a = 200;
$b = 300;
if ($a > $b + $b != 3)
    print "Correct";

else
print "Incorrect";
?>

output is: Correct输出是:正确

Can someone help me understand why the output became "Correct"?有人可以帮我理解为什么输出变成“正确”吗?

To understand what is happening here, you need to look at the list ofoperator precendence to see what is being evaluated first.要了解此处发生的情况,您需要查看运算符优先级列表以了解首先评估的内容。 It's not left to right.它不是从左到右。 The order of the operators in your if statement are as follows: if 语句中运算符的顺序如下:

  1. + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ - arithmetic (unary + and -), increment/decrement, bitwise, type casting and error control + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ - 算术(一元 + 和 -)、递增/递减、按位、类型转换和错误控制
  2. < <= > >= - associative comparison < <= > >= - 关联比较
  3. == != === !== <> <=> - non associative comparison == != === !== <> <=> - 非关联比较

So in essence, your if statement breaks down to this:因此,从本质上讲,您的 if 语句分解为:

(($a > ($b + $b)) != 3)

With your values becomes随着你的价值观变成

((200 > (300 + 300)) != 3)
((200 > 600) != 3)
(false != 3)

So of course, false is not 3, and makes your if statement correct.所以当然, false 不是 3,并使您的 if 语句正确。 If you want to evaluation 200 is greater than 300 AND 300 is not 3 , then you need the logical AND operator, or && , which would be如果要评估200 is greater than 300 AND 300 is not 3 ,则需要逻辑 AND 运算符或&& ,即

($a > $b && $b != 3)

which would print Incorrect这将打印Incorrect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM