[英]Why chr(0x00) is considered as true in PHP?
0x00 is known to be the null character. 已知0x00是空字符。
Then why in PHP (bool) null
returns false, but (bool) chr(0x00)
returns true ? 那么为什么在PHP
(bool) null
返回false,但是(bool) chr(0x00)
返回true?
In the other hand, (bool)intval(chr(0x00))
returns false. 另一方面,
(bool)intval(chr(0x00))
返回false。
The above is valid for all PHP versions between 5.4 and 7.0.0 beta2, so there must be a reason. 以上内容适用于5.4和7.0.0 beta2之间的所有PHP版本,因此必须有一个原因。
Edit: I'm asking this question, because I have a bit(1)
column in MySQL, and chars 0x00 or 0x01 are returned. 编辑:我问这个问题,因为我在MySQL中有一个
bit(1)
列,并返回字符0x00或0x01。
if ($test['bit1column'])
will always pass, because both chars are considered as true, so I'm forced to do an if ($test['bit1column'] === chr(0x01))
. if ($test['bit1column'])
将始终通过,因为两个字符都被认为是真的,所以我被迫做一个if ($test['bit1column'] === chr(0x01))
。
This is correct at least for PHP 5.6 with MySQL 5.5.44. 至少对于使用MySQL 5.5.44的PHP 5.6,这是正确的。 Why?
为什么? I can't see any logic here.
我在这里看不到任何逻辑。
Then why in PHP (bool) null returns false, but (bool) chr(0x00) returns true ?
那么为什么在PHP(bool)中null返回false,但是(bool)chr(0x00)返回true?
it's because chr(0x00)
gives you a one char long string: 这是因为
chr(0x00)
给你一个char长字符串:
$ php -r "var_dump(chr(0x00));"
string(1) ""
and then ( as per documentation ) the only case string can give false
when casted to boolean is either the empty one (so length is 0) or the string holding "0" as its content: 然后( 根据文档 ),当转换为布尔值时,唯一的case字符串可以给出
false
是空的(所以length是0)或者是“0”作为其内容的字符串:
When converting to boolean, the following values are considered FALSE:
转换为布尔值时,以下值被视为FALSE:
the empty string, and the string "0"
空字符串,字符串“0”
This is neither the case here as our string is not holding 0
nor is empty as it holds 1 character. 这不是这里的情况,因为我们的字符串不保持
0
也不是空的,因为它包含1个字符。 So it cannot be false
and therefore is true
. 所以它不可能是
false
,因此是true
。
EDIT 编辑
I assume you expected C
/ C++
like behaviour where strings are 0x00
terminated. 我假设您期望
C
/ C++
行为,其中字符串是0x00
终止。 This is not the case in PHP. PHP中不是这种情况。
In PHP the following things are false
: 在PHP中,以下内容是
false
:
""
(an empty string) ""
(空字符串) 0
(0 as an integer) 0
(0为整数) 0.0
(0 as a float) 0.0
(0作为浮点数) "0"
(0 as a string) "0"
(0作为字符串) null
false
array()
(an empty array) array()
(一个空数组) Everything else is true
. 其他一切都是
true
。 chr(0x00)
results in a string with a single character (the NUL
byte). chr(0x00)
产生一个带有单个字符的字符串( NUL
字节)。 That's not an empty string and not a string with the character 0
, so it does not qualify as false
. 这不是一个空字符串而不是一个字符为
0
的字符串,所以它不符合false
。
Trying to cast the string "\\0"
( NUL
byte) to an int
results in 0
, because there's no parseable integer in the string, so the result is 0
. 尝试将字符串
"\\0"
( NUL
字节) NUL
转换为int
导致0
,因为字符串中没有可解析的整数,因此结果为0
。 0
is false
. 0
是false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.