Error Identifier: unset.offset
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);
function doFoo(): void
{
$scalar = 3;
unset($scalar['a']);
}
Why is it reported? #
The unset() call attempts to remove an array offset from a type that either does not support offset access or does not have the specified offset. This indicates a logic error – the variable is not the array that was expected, or the offset does not exist on the given type.
In the example above, $scalar is an int, which does not support offset access. Attempting to unset an offset on it is meaningless.
How to fix it #
Make sure unset() is called on a variable that supports offset access and has the given offset:
<?php declare(strict_types = 1);
function doFoo(): void
{
- $scalar = 3;
- unset($scalar['a']);
+ $data = ['a' => 1, 'b' => 2];
+ unset($data['a']);
}
Or verify the type of the variable before unsetting:
<?php declare(strict_types = 1);
-/** @param iterable<int, int> $iterable */
-function doBar(iterable $iterable): void
+/** @param array<int, int> $data */
+function doBar(array $data): void
{
- unset($iterable['string']);
+ unset($data[0]);
}
How to ignore this error #
You can use the identifier unset.offset to ignore this error using a comment:
// @phpstan-ignore unset.offset
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: unset.offset
Rules that report this error #
- PHPStan\Rules\Variables\UnsetRule [1]