Error Identifier: array.invalidKey
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);
$key = new stdClass();
$array = [$key => 'value'];
Why is it reported? #
The value used as an array key is not a valid array key type. PHP only allows int, string, bool, float, and null as array keys (with bool, float, and null being cast to int or string). Using any other type, such as an object or an array, as an array key results in a fatal error at runtime.
In the example above, an stdClass object is used as an array key, which is not allowed.
How to fix it #
Use a valid array key type such as int or string:
<?php declare(strict_types = 1);
-$key = new stdClass();
-$array = [$key => 'value'];
+$key = 'my_key';
+$array = [$key => 'value'];
How to ignore this error #
You can use the identifier array.invalidKey to ignore this error using a comment:
// @phpstan-ignore array.invalidKey
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: array.invalidKey
Rules that report this error #
- PHPStan\Rules\Arrays\InvalidKeyInArrayItemRule [1]