In PHP, you can use array syntax to access string indexes. The following program
<?php
$foo = "Hello";
echo $foo[0],"\n";
?>
echos out
H
However, if you access the first character of a zero length string
<?php
$bar = "";
$bar[0] = "test";
var_dump($bar);
?>
PHP turns your string into an array. The above code produces
array(1) {
[0] =>
string(4) "test"
}
i.e. my zero length string was cast to an array. Similar "accessing an undefined index of a string" examples don't produce this casting behavior.
$bar = " ";
$bar[1] = "test";
var_dump($bar);
Produces the string t
. i.e. $bar
remains a string, and is not converted into an array.
I get these sorts of unintuitive edge cases are inevitable when the language needs to infer and/or automatically cast variable for you, but does anyone know what's going on behind the scenes here?
i.e. What is happening at the C/C++ level in PHP to make this happen. Why does my variable get turned into an array.
PHP 5.6, if that matters.