Error Identifier: offsetAccess.notFound
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 = ['name' => 'John', 'age' => 30];
echo $array['email'];
}
Why is it reported? #
The code accesses an array or object offset that does not exist on the given type. This access would result in an undefined offset warning (or return null for ArrayAccess implementations) at runtime.
In the example above, the array has keys name and age, but the code tries to access the key email which does not exist.
How to fix it #
Use an offset that exists on the type:
$array = ['name' => 'John', 'age' => 30];
-echo $array['email'];
+echo $array['name'];
If the offset might not exist, check for its presence first:
$array = ['name' => 'John', 'age' => 30];
-echo $array['email'];
+if (isset($array['email'])) {
+ echo $array['email'];
+}
Or add the missing key to the array:
-$array = ['name' => 'John', 'age' => 30];
+$array = ['name' => 'John', 'age' => 30, 'email' => 'john@example.com'];
echo $array['email'];
How to ignore this error #
You can use the identifier offsetAccess.notFound to ignore this error using a comment:
// @phpstan-ignore offsetAccess.notFound
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: offsetAccess.notFound