$a = '86';
var_dump($a); //ouput string(2) "86"
var_dump($a['wtf']); //output string(1) "8"
The second oputput is strange although that is equivalent to
var_dump($a[0]); ////output string(1) "8"
Can somebody explain me why var_dump($a['wtf']); output string(1) "8" ?
$a is a string.
A string in php can be regarded as an array of chars (so $a[0] == '8' and $a[1] == '6')
Now, you tried to access the string at place ['wtf'], since PHP expects a number there, it will try to convert 'wtf' to number. Since there is no digit in this string, it is regarded as 0.
'wtf1' is converted to 0 as it checks the first characters (thanks to sad bube)
'1wtf' is converted to 1
'100' is converted to 100
'dfsdgrgergregr' is converted to 0
Probably it converts 'wtf' string to integer 0...or something related. But Why do you have to use $a['wtf']?
PHP has weak typing, i.e. if you pass a string where it expects an integer, it will transparently convert it to integer, which, in most cases, is good, since it allows cleaner code. But then it also allows more errors, of course.
This is (probably) the reason, why addition and concatenation are done by different operators (+
will convert both operands to numbers, .
will convert both to strings).
As previously pointed out, you are trying to access a string index, which can only be an integer, so 'wtf'
is correctly converted to 0
and the first letter is returned. If you passed, say, '1o1wut'
, it would be converted to 1
.