Error Identifier: array.duplicateKey
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);
$array = [
'foo' => 1,
'bar' => 2,
'foo' => 3,
];
Why is it reported? #
The array literal contains duplicate keys. When an array has duplicate keys, PHP silently overwrites the earlier value with the later one. This is usually a mistake – either the key or the value is wrong. Only the last value for the duplicate key will be preserved.
In the example above, the key 'foo' appears twice. The first value 1 will be silently overwritten by 3.
How to fix it #
Use unique keys for each array entry:
<?php declare(strict_types = 1);
$array = [
'foo' => 1,
'bar' => 2,
- 'foo' => 3,
+ 'baz' => 3,
];
Or remove the duplicate entry if it was unintentional:
<?php declare(strict_types = 1);
$array = [
'foo' => 1,
'bar' => 2,
- 'foo' => 3,
];
How to ignore this error #
You can use the identifier array.duplicateKey to ignore this error using a comment:
// @phpstan-ignore array.duplicateKey
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.duplicateKey
Rules that report this error #
- PHPStan\Rules\Arrays\DuplicateKeysInLiteralArraysRule [1]