为什么$ string [0] =''不会导致$ string [0] ===''?
$s = 'abc';
$s[0] = '';
if ($s[0] !== '') {
echo 'emmm';
}
Why $string[0] = '' is not resulting $string[0] === ''?
seems like $string[0] === "\0", but more confusing..
$ s ='abc';
$ s [0] ='';
if( $ s [0]!==''){
echo'emmm';
}
code> pre>
为什么$ string [0] =''不是 结果$ string [0] ===''? p>
好像是$ string [0] ===“\ 0”,但更令人困惑.. p>
$s[0]
gives access to a single character of the string. ''
is not a character, it's a string, so the assignment fails. You get the exact same behavior if you try to assign FALSE
to $s[0]
. It looks like PHP does its best to convert whatever value you assign into a single character. If you assign a non-empty string, it will use the first character. If you assign a number, it will use the first digit. If you assign the value TRUE
, it will use 1
.
when you set $s[0] == '', the string has changed, it's '\0bc', and you know '\' only escaped between "", so it's "\0" not '\0', and '' means \0.
The manual does specify what happens:
Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits
E_NOTICE
. Negative offset emitsE_NOTICE
in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assignsNULL
byte.
(Emphasis added)
The $str[42] = ..
notation replaces exactly one byte in the string with exactly one byte. All the special cases are noted in the manual, like the case of assigning nothing (an empty string), in which case a NUL
byte is assigned instead.
Why $string[0] = '' is not resulting $string[0] === ''?
Because in this case empty string is replaced with ASCII code NULL-byte
(\0
, ASCII 0
or 0x00
). And when you set part of the string with empty string, it is replace with 0x00
.
If you wish to compare nullable byte, try this:
if ($s[0] !== chr('0')) {
# or
if ($s[0] !== "\0") {