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"];
|
2020-03-20 20:20:54 +01: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 20:20:54 +01:00
|
|
|
|
2020-03-21 00:19:24 +01:00
|
|
|
```php
|
|
|
|
<?php
|
|
|
|
|
2020-03-21 14:24:41 +01:00
|
|
|
...
|
|
|
|
|
2020-03-20 20:20:54 +01:00
|
|
|
echo $arr["b"] ?? 0;
|
|
|
|
```
|
|
|
|
|
|
|
|
Alternatively, you can ensure that the array offset always exists:
|
2020-03-19 17:32:49 +01:00
|
|
|
|
2020-03-20 20:20:54 +01:00
|
|
|
```php
|
2020-03-21 00:19:24 +01:00
|
|
|
<?php
|
|
|
|
|
2020-03-20 20:20:54 +01:00
|
|
|
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
|
|
|
```
|