0x00 is known to be the null character.
Then why in PHP (bool) null
returns false, but (bool) chr(0x00)
returns true ?
In the other hand, (bool)intval(chr(0x00))
returns false.
The above is valid for all PHP versions between 5.4 and 7.0.0 beta2, so there must be a reason.
Edit: I'm asking this question, because I have a bit(1)
column in MySQL, and chars 0x00 or 0x01 are returned.
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))
.
This is correct at least for PHP 5.6 with MySQL 5.5.44. Why? I can't see any logic here.
Then why in PHP (bool) null returns false, but (bool) chr(0x00) returns true ?
it's because chr(0x00)
gives you a one char long string:
$ 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:
When converting to boolean, the following values are considered FALSE:
the empty string, and the string "0"
This is neither the case here as our string is not holding 0
nor is empty as it holds 1 character. So it cannot be false
and therefore is true
.
EDIT
I assume you expected C
/ C++
like behaviour where strings are 0x00
terminated. This is not the case in PHP.
In PHP the following things are false
:
""
(an empty string) 0
(0 as an integer) 0.0
(0 as a float) "0"
(0 as a string) null
false
array()
(an empty array) Everything else is true
. chr(0x00)
results in a string with a single character (the NUL
byte). That's not an empty string and not a string with the character 0
, so it does not qualify as 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
is false
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.