Error Identifier: isset.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
{
$array = ['a' => 1, 'b' => 2];
if (isset($array['a'])) {
echo $array['a'];
}
}
Why is it reported? #
The isset() check (or ?? null-coalescing operator, or empty()) is used on an array offset that PHPStan can determine either always exists and is not nullable, or never exists. When the offset is always present and its value is never null, the isset() call is redundant – it always evaluates to true. When the offset can never exist on the given type, the check always evaluates to false.
How to fix it #
If the offset always exists, remove the unnecessary isset() check:
$array = ['a' => 1, 'b' => 2];
-if (isset($array['a'])) {
- echo $array['a'];
-}
+echo $array['a'];
If the offset never exists, fix the key or the source of the data:
$array = ['a' => 1, 'b' => 2];
-if (isset($array['c'])) {
+if (isset($array['a'])) {
// ...
}
If the array contents are dynamic and the check is meaningful, use a broader type annotation to tell PHPStan about the possible keys:
-/** @var array{a: int, b: int} $array */
+/** @var array<string, int> $array */
How to ignore this error #
You can use the identifier isset.offset to ignore this error using a comment:
// @phpstan-ignore isset.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: isset.offset