索引空变量时未引发php undefined索引通知 [英] php undefined index notice not raised when indexing null variable
问题描述
我很想知道PHP是否打算执行以下行为.并且,如果有意的话,是否可以通过在空变量中创建索引来初始化数组(如第一个代码段中所示)?
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);
此输出
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);
推荐答案
如果数组为null,PHP将不会尝试进行比较.
PHP won't attempt the comparison if the array is null.
在第二种情况下,因为设置了数组,所以确实发生了比较.PHP不会检查它是否为空.
In the second circumstance, a comparison does occur because the array is set. PHP does not check to see if it is empty.
您的三元尝试访问变量$ arr ["blah"],而不在进行比较之前不检查变量是否已设置.
Your ternary is attempting to access the variable $arr["blah"], not checking to see if it is set before doing a comparison.
正确的写法是:
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);
这篇关于索引空变量时未引发php undefined索引通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!