Home » Php » arrays – php undefined index notice not raised when indexing null variable

arrays – php undefined index notice not raised when indexing null variable

Posted by: admin July 12, 2020 Leave a comment

Questions:

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);
How to&Answers:

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

Answer:

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.