php if-else势

发布于 2025-02-07 13:24:58 字数 202 浏览 2 评论 0原文

代码:

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

else
print "Incorrect";
?>

输出是:正确

有人可以帮助我理解为什么输出变得“正确”?

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"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

御守 2025-02-14 13:24:58

要了解这里发生的事情,您需要查看操作员预定首先要评估什么。它不是向右。 if语句中运算符的顺序如下:

  1. + - ++ - 〜(int)(float)(string)(arnay)(array)(object)(bool) @ - arithmetic(Unary) + and-),增量/减少,位,类型铸造和错误控制
  2. &lt; &lt; =&gt; &gt; = - 关联比较
  3. ==!===== ==&lt;&gt; &lt; =&gt; - 非关联比较

本质上,您的if语句对此进行了分解:

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

随着您的价值观

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

,当然,false不是3,并且使您的if语句正确。如果您想评估200大于300和300不是3,那么您需要逻辑和操作员,或&amp;&amp;,它将

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

打印出来不正确

To understand what is happening here, you need to look at the list of operator 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:

  1. + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ - arithmetic (unary + and -), increment/decrement, bitwise, type casting and error control
  2. < <= > >= - associative comparison
  3. == != === !== <> <=> - non associative comparison

So in essence, your if statement breaks down to this:

(($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. 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

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

which would print Incorrect

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文