当引用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"];
Run Code Online (Sandbox Code Playgroud)
为什么它返回与[0]相同的结果?