Php undefined index notification does not occur when indexing a null variable

I am curious to know if the following behavior is intended in PHP or not. And, if this is assumed, it is considered acceptable to initialize an array from a null variable by creating an index into it (as is done in the first code fragment)?

error_reporting(E_ALL); $arr = null; echo ($arr["blah"]===null) ? "null" : $arr["blah"]; $arr["blah"] = "somevalue"; echo "<br>"; echo ($arr["blah"]===null) ? "null" : $arr["blah"]; var_dump ($arr); 

Displays

 null somevalue array (size=1) 'blah' => string 'somevalue' (length=9) 

However, if the array is initialized first (see the code below), I get the same result, but the notification "Undefined Index" is indicated on the first attempt $arr["blah"]

 error_reporting(E_ALL); $arr = array(); echo ($arr["blah"]===null) ? "null" : $arr["blah"]; $arr["blah"] = "somevalue"; echo "<br>"; echo ($arr["blah"]===null) ? "null" : $arr["blah"]; var_dump ($arr); 
+7
source share
2 answers

PHP will not try to compare if the array is null.

In the second case, the comparison occurs because the array is specified. PHP does not check if it is empty.

The tee is trying to access the $ arr ["blah"] variable, rather than checking to see if it is set before doing the comparison.

The correct way to write:

 error_reporting(E_ALL); $arr = array(); if(isset($arr["blah"])) echo ($arr["blah"]===null) ? "null" : $arr["blah"]; $arr["blah"] = "somevalue"; echo "<br>"; if(isset($arr["blah"])) echo ($arr["blah"]===null) ? "null" : $arr["blah"]; var_dump ($arr); 
0
source

In fact, John Wargo was right. If the variable is null , accessing it as if it were an array would simply return null without notification. This will change in the next version 7.4, after which a notification will appear.

 Notice: Trying to access array offset on value of type null 

The actual result remains the same.

0
source

Source: https://habr.com/ru/post/958165/


All Articles