php undefined index notice not raised when indexing null variable

三世轮回 提交于 2021-02-07 12:29:19

问题


I'm curious to know if the following behaviour in PHP is intended or not. And, if it is intended, 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 snippet)?

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);

This outputs

null
somevalue

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

However, if the array is initialized first (see code below), I get the exact same output, but an "Undefined Index" notice is given when I first try $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);

回答1:


PHP won't attempt the comparison if the array is null.

In the second circumstance, a comparison does occur because the array is set. PHP does not check to see if it is empty.

Your ternary is attempting to access the variable $arr["blah"], not checking to see if it is set before doing a comparison.

The proper way to write this would be:

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);



回答2:


Actually, John Vargo was correct. If a variable is null, accessing it as if it were an array will simply return null without notices. This will change in the upcoming 7.4 version, then it will produce a notice.

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

The actual output is still the same.



来源:https://stackoverflow.com/questions/20009076/php-undefined-index-notice-not-raised-when-indexing-null-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!