Why does treating integers as arrays ($int[$index]) not raise any errors in PHP?
I originally thought; it typecasts $int
to a string because []
is another way of accessing string positions. Seems plausible that that wouldn't generate an error:
$string 'Hello';
echo $string[0]; // H
However, that's not the case:
$int = 1;
echo $int[0];
Outputs nothing and var_dump($int[0])
returns NULL
.
Interestingly, the same behavior is exhibited for bool
and float
and the operation used is FETCH_DIM_R
which is Fetch the value of the element at "index" in "array-value" to store it in "result".
From the manual Arrays:
Note: Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.
Similar to this phenomenon, where no error is generated. Bugs #68110 and #54556:
$array['a'] = null;
echo $array['a']['non-existent'];
Not surprising that assigning doesn't work:
$int = 1;
$int[0] = 2;
Warning: Cannot use a scalar value as an array
So PHP is actually attempting to access the int
, bool
, float
as an array but not generating an error. This is from at least version 4.3.0 to 7.2.2.