开发者

PHP and access to string like to assoc array

Is that logical behavior?

$str = 'string';  
$res = $str['some_key'];  
echo (int)isset($str['some_key']); // 1  
echo $res; // 's'  

It's a bug or unclear feature开发者_JAVA百科?


It is a "feature". When using $string[$index], $index is treated as integer, so 'some_key' is converted to 0. That's also why you get 's' (first letter of $str) in $res.

$str = 'Lorem';
var_dump($str['key']); // L, because (int)'key' is 0
var_dump($str['0key']); // L
var_dump($str['1key']); // o, because (int)'1key' is 1
var_dump($str['2key']); // r
var_dump($str['3key']); // e, because (int)'3key' is 3
var_dump($str['4key']); // m
var_dump($str['5key']); // Notice:  Uninitialized string offset: 5 in sandbox\index.php on line 20


Accessing strings like arrays is a feature.
Strings only have numeric offsets, any "key" you use is cast to an int.
Non-numeric strings cast to the int 0.
Hence $str["foo"] is equivalent to $str[0].

So there is a logic, whether you want to call it logical or not is up to you.
But if you're accessing strings with string keys, something's wrong with your code anyway. ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜