1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 12:55:26 +01:00
psalm/docs/running_psalm/issues/PossiblyUndefinedArrayOffset.md

42 lines
589 B
Markdown
Raw Normal View History

2020-03-19 17:32:49 +01:00
# PossiblyUndefinedArrayOffset
Emitted when trying to access a possibly undefined array offset
```php
2020-03-21 00:13:46 +01:00
<?php
2020-03-19 17:32:49 +01:00
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 does not exist:
2020-03-21 00:19:24 +01:00
```php
<?php
...
echo $arr["b"] ?? 0;
```
Alternatively, you can ensure that the array offset always exists:
2020-03-19 17:32:49 +01:00
```php
2020-03-21 00:19:24 +01:00
<?php
if (rand(0, 1)) {
$arr = ["a" => 1, "b" => 2];
} else {
$arr = ["a" => 3, "b" => 0];
}
echo $arr["b"];
2020-03-19 17:32:49 +01:00
```