mirror of
https://github.com/danog/psalm.git
synced 2024-12-15 02:47:02 +01:00
ea52b9d23a
While I was searching for some code, ran across these.
42 lines
589 B
Markdown
42 lines
589 B
Markdown
# 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 does not 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"];
|
|
```
|