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);
Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.
Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.
The error can be avoided by using the isset() function. This function will check whether the index variables are assigned a value or not, before using them.
Undefined index errors can be resolved by making use of a function called isset() function. Undefined index errors can be ignored by updating the option error_reporting to ~E_NOTICE to disable the reporting of notices.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With