Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
$a = ['foo' => 1, 'bar' => 2];
echo $a['1']; // key '1' (string) will be cast to 1 (int)
echo $a[null]; // key null will be cast to '' (string)
echo $a[2.5]; // key 2.5 (float) will be cast to 2 (int)
echo $a[true]; // key true (bool) will be cast to 1 (int)
Why is it reported? #
PHP silently casts array keys to int or string when accessing array elements. A numeric string like '1' is cast to the integer 1, null becomes the empty string '', floats are truncated to integers, and booleans become 0 or 1. This means the accessed key may not match what the developer intended, leading to unexpected values or missing entries.
This rule is only active on the PHPStan playground.
Learn more: Why Array String Keys Are Not Type-Safe in PHP
How to fix it #
Use array keys that match the expected type without implicit casting:
$a = [1 => 'one', 2 => 'two'];
-echo $a['1'];
+echo $a[1];
For null keys, use the explicit string equivalent:
-echo $a[null];
+echo $a[''];
For float keys, use the truncated integer directly:
-echo $a[2.5];
+echo $a[2];
For boolean keys, use the corresponding integer:
-echo $a[true];
+echo $a[1];
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Playground\ArrayDimCastRule [1]