PHP String Index $str["test"] same as $str[0]? -
this question has answer here:
- why strings behave array in php 5.3? 1 answer
when referring element inside php string array, using square brackets [ ] can use number [2] select specific character string. however, when using string index ["example"], returns same result [0].
<?php $str="hello world."; echo $str; // echos "hello world." expected. echo $str[2]; // echos "l" expected. echo $str["example"]; // echos "h", not expected. $arr=array(); $arr["key"]="test." echo $arr["key"]; // echos "test." expected. echo $arr["invalid"]; // gives "undefined index" error expected. echo $arr["key"];
why return same result [0]?
php uses type juggling convert variables of non fitting type fitting one. in case, php expects index numeric, integer exact. if give string, try parse number. if not possible, defaults zero.
sidenote: if give string "9penguins", 9.
php manual on type juggling: http://php.net/manual/de/language.types.type-juggling.php
Comments
Post a Comment