if语句不适用于php中的false [英] The if statement doesn't work for false in php
问题描述
当试图熟悉PHP中的if
语句时,发生了这种情况.
第一次我在下面尝试此代码.
When trying to get familiar with if
statement in PHP, this happened.
First time i tried this code below.
if(true) {echo 'true';} else {echo 'false';}
当条件为true
时,输出为true
.同样,当条件为false
(if(false)
)时,它将回显false
.
And the output was true
when the condition is true
. Again, when the condition is false
(if(false)
) it echos false
.
但是我尝试了同样的方法,同时使用变量作为条件,同时更改了变量的值.
But i tried the same, using a variable as the condition, while changing the value of the variable.
$con='false';
if($con){echo 'true';} else{echo 'false';}
在这种情况下,即使变量值为false
或true
,输出也为true
.同时,当使用1
和0
代替true
和false
时,if statement
可以正常工作.为什么会这样?
At this situation the output is true
even when the variable value is false
or true
. At the same time, the if statement
working fine when 1
and 0
is used instead true
and false
. Why is this happening?
推荐答案
PHP在if表达式中做了一些偷偷摸摸的事情.以下值被认为是FALSE:
PHP does some sneaky things in the if expression. The following values are considered FALSE:
- 布尔值FALSE本身
- 整数0(零)
- 浮点数0.0(零)
- 空字符串和字符串"0"
- 具有零个元素的数组
- 具有零成员变量的对象(仅PHP 4)
- 特殊类型NULL(包括未设置的变量)
- 从空标签创建的SimpleXML对象
其他所有值都被视为TRUE(包括任何资源).
Every other value is considered TRUE (including any resource).
您实际上传递的是一个字符串,该字符串表示单词false,而不是值false.因为不在上面的列表中,所以实际上被认为是正确的!
You're actually passing a string that says the word false, rather than the value false itself. Because that isn't in the above list, it is actually considered true!
这篇关于if语句不适用于php中的false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!