PHP字符串索引$ str [“test”]与$ str [0]相同? [重复]

This question already has an answer here:

When referring to an element inside a PHP string like an array, using square brackets [ ] you can use a number like [2] to select a specific character from the string. However, when using a string index like ["example"], it always returns the same result as [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"];

Why does it return the same result as [0]?

</div>

PHP uses type juggling to convert variables of a non fitting type to a fitting one. In your case, PHP expects your index to be a numeric, an integer to be exact. If you give it a string, it will try to parse it as a number. If not possible, it defaults to zero.

Sidenote: If you give it a string like "9penguins", you will get a 9.

PHP Manual on type juggling: http://php.net/manual/de/language.types.type-juggling.php