2020-03-19 12:32:49 -04:00
|
|
|
# PossiblyUndefinedArrayOffset
|
|
|
|
|
|
|
|
Emitted when trying to access a possibly undefined array offset
|
|
|
|
|
|
|
|
```php
|
2020-03-20 19:13:46 -04:00
|
|
|
<?php
|
|
|
|
|
2020-03-19 12:32:49 -04:00
|
|
|
if (rand(0, 1)) {
|
|
|
|
$arr = ["a" => 1, "b" => 2];
|
|
|
|
} else {
|
|
|
|
$arr = ["a" => 3];
|
|
|
|
}
|
|
|
|
|
|
|
|
echo $arr["b"];
|
2020-03-20 15:20:54 -04:00
|
|
|
```
|
|
|
|
|
|
|
|
## How to fix
|
|
|
|
|
2020-08-08 14:09:41 +02:00
|
|
|
You can use the null coalesce operator to provide a default value in the event the array offset does not exist:
|
2020-03-20 15:20:54 -04:00
|
|
|
|
2020-03-20 19:19:24 -04:00
|
|
|
```php
|
|
|
|
<?php
|
|
|
|
|
2020-03-21 09:24:41 -04:00
|
|
|
...
|
|
|
|
|
2020-03-20 15:20:54 -04:00
|
|
|
echo $arr["b"] ?? 0;
|
|
|
|
```
|
|
|
|
|
|
|
|
Alternatively, you can ensure that the array offset always exists:
|
2020-03-19 12:32:49 -04:00
|
|
|
|
2020-03-20 15:20:54 -04:00
|
|
|
```php
|
2020-03-20 19:19:24 -04:00
|
|
|
<?php
|
|
|
|
|
2020-03-20 15:20:54 -04:00
|
|
|
if (rand(0, 1)) {
|
|
|
|
$arr = ["a" => 1, "b" => 2];
|
|
|
|
} else {
|
|
|
|
$arr = ["a" => 3, "b" => 0];
|
|
|
|
}
|
|
|
|
|
|
|
|
echo $arr["b"];
|
2020-03-19 12:32:49 -04:00
|
|
|
```
|