为什么在 PHP 中 true 大于 3

2021-12-31 00:00:00 types casting php

我想知道为什么 PHP 中的以下语句返回 true?

I am wondering why following statement in PHP is returning true?

true>=4

例如这样的行会回显 1

echo true>=4;

谁能解释一下这背后的逻辑?

Can anyone explain me the logic behind this?

推荐答案

除了 Davids 的回答之外,我还想添加一些东西来增加深度.

In addition to Davids answer, I thought to add something to give a little more depth.

PHP 与其他编程语言不同,如果您不小心操作符/语法,您可能会陷入像您遇到的那种棘手的坑洞.

PHP unlike other programming languages, if your not careful with your operators/syntax you can fall into tricky pot holes like the one you experience.

正如大卫所说,

4 也是真(因为它非零),真等于真,所以它也大于或等于 true.

4 is also true (because it's non-zero), and true is equal to true, so it's also greater than or equal to true.

考虑到这一点真大于假.

真 = 1

假=0

举个例子:

$test = 1;
if ($test == true){
echo "This is true"; 
}else{
echo "This is false";
}

上面会输出

这是真的

但是如果你接受这个:

$test = 1;
if ($test === true){
echo "This is true"; 
}else{
echo "This is false";
}

上面会输出:

这是假的

添加的等号查找完全匹配,从而查找 integer 1 而不是 PHP 读取 1 为真.

The added equals sign, looks for an exact match, thus looking for the integer 1 instead of PHP reading 1 as true.

我知道这有点离题,但只是想解释一下 PHP 包含的一些坑.

希望对您有所帮助

回答你的问题:

回声真>=4;

您看到 1 作为输出的原因是因为 true/false 被解释为数字(见上文)

Reason you are seeing 1 as output, is because true/false is interpreted as numbers (see above)

无论你是在做 echo true>=4 还是只是 echo true; php 都将 true 设为 1,将 false 设为 0

Regardless if your doing echo true>=4 or just echo true; php puts true as 1 and false as 0

相关文章