1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-03 10:07:52 +01:00
psalm/docs/running_psalm/issues/PossiblyUndefinedArrayOffset.md
2020-03-21 09:24:41 -04:00

42 lines
590 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# PossiblyUndefinedArrayOffset
Emitted when trying to access a possibly undefined array offset
```php
<?php
if (rand(0, 1)) {
$arr = ["a" => 1, "b" => 2];
} else {
$arr = ["a" => 3];
}
echo $arr["b"];
```
## How to fix
You can use the null coalesce operator to provide a default value in the event the array offset doesnt exist:
```php
<?php
...
echo $arr["b"] ?? 0;
```
Alternatively, you can ensure that the array offset always exists:
```php
<?php
if (rand(0, 1)) {
$arr = ["a" => 1, "b" => 2];
} else {
$arr = ["a" => 3, "b" => 0];
}
echo $arr["b"];
```