PHP字符串索引$str["test"]与$str[0]相同


PHP String Index $str["test"] same as $str[0]?

当引用PHP字符串(如数组)中的元素时,使用方括号[]可以使用像[2]这样的数字从字符串中选择特定的字符。但是,当使用像["example"]这样的字符串索引时,它总是返回与[0]相同的结果。

<?php
$str="Hello world.";
echo $str; // Echos "Hello world." as expected.
echo $str[2]; // Echos "l" as expected.
echo $str["example"]; // Echos "H", not expected.
$arr=array();
$arr["key"]="Test."
echo $arr["key"]; // Echos "Test." as expected.
echo $arr["invalid"]; // Gives an "undefined index" error as expected.
echo $arr["key"];

为什么它返回与[0]相同的结果?

PHP使用类型杂耍将非拟合类型的变量转换为拟合类型。在您的例子中,PHP期望您的索引是一个数字,一个精确的整数。如果你给它一个字符串,它会尝试把它解析成一个数字。如果不可能,则默认为零。

旁注:如果你给它一个像"9penguins"这样的字符串,你会得到一个9。