Error Identifier: arrayUnpacking.stringOffset
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 = [1, 2, 3];
$b = ['key' => 'value'];
$merged = [...$a, ...$b];
Why is it reported? #
Before PHP 8.1, array unpacking with the spread operator (...) only supported arrays with integer keys. Using array unpacking on an array with string keys results in a fatal error in PHP versions prior to 8.1.
In the example above, $b has the string key 'key', so unpacking it with ...$b is not supported on the configured PHP version.
How to fix it #
Use array_merge() instead of array unpacking when dealing with string-keyed arrays:
<?php declare(strict_types = 1);
$a = [1, 2, 3];
$b = ['key' => 'value'];
-$merged = [...$a, ...$b];
+$merged = array_merge($a, $b);
Or upgrade the project’s PHP version to 8.1 or later, which supports array unpacking with string keys. Update the phpVersion setting in the PHPStan configuration accordingly.
How to ignore this error #
You can use the identifier arrayUnpacking.stringOffset to ignore this error using a comment:
// @phpstan-ignore arrayUnpacking.stringOffset
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: arrayUnpacking.stringOffset
Rules that report this error #
- PHPStan\Rules\Arrays\ArrayUnpackingRule [1]