<?php
error_reporting(-1);
$a = array('key' => '2');
$a = $a['key'];
var_dump($a);
echo $a['key'], "\n";
?>
I expected the code to throw empty string or a warning saying key isn’t present, but the code prints 2;
PHP 5.3.10-1
Update1 : Adding var_dump and error_reporting.
Output is
hari@hari-laptop:~$ php run.php
string(1) "2"
2
$ais a string that holds the value"2".Strings in PHP can be indexed to access their characters using square brackets. For example:
When the index is a string, PHP tries to parse it as an integer. If the string is not a number, parsing will give
0. Hence, The zero’th index, representing the first character is used. (In PHP 5.4 and up, it gives a warning). In your case, you got “2” because$a['any_stuff']= first character ='2'From PHP manual: