开发者

Strange PHP array behaviour [duplicate]

This question already has answers开发者_高级运维 here: Closed 10 years ago.

Possible Duplicate:

PHP String in Array Only Returns First Character

I've got following problem. When I run script below I got string(1) "F" as an output. How is that possible? No error, notice displayed.. nothing. Key whatever doesn't exist in $c. Can you explain that?

   <?php
   $c = 'FEEDBACK_REGISTER_ACTIVATION_COMPLETED_MSG';
   var_dump ($c['whatever']);
   ?>

I'm having this issue on PHP 5.3.3. (LINUX)


PHP lets you index on strings:

$str = "Hello, world!";
echo $str[0]; // H
echo $str[3]; // l

PHP also converts strings to integers implicitly, but when it fails, uses zero:

$str = "1";
echo $str + 1; // 2
$str = "invalid";
echo $str + 1; // 1

So what it's trying to do is index on the string, but the index is not an integer, so it tries to convert the string to an integer, yielding zero, and then it's accessing the first character of the string, which happens to be F.


Through Magic type casting of PHP when an associative array can not find the index, index itself is converted to int 0 and hence it is like if

$sample = 'Sample';

$sample['anystring'] = $sample[0];

so if o/p is 'S';

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜