Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined Index Behavior

Tags:

arrays

php

If I have an array in PHP that is currently null, shouldn't accessing an undefined index present an E_NOTICE level error?

If I have the following snippet of code:

$myArray = null;
echo $myArray['foo']['bar'];

I would expect an error but it runs without issue. I've verified my log level to be set to E_ALL. Is there something I'm missing or is PHP happy returning null for undefined indexes as long as you aren't trying to modify the data?

like image 220
Dan W. Avatar asked Aug 05 '11 15:08

Dan W.


People also ask

What is an undefined index?

When using them, you might encounter an error called “Notice: Undefined Index”. This error means that within your code, there is a variable or constant that has no value assigned to it. But you may be trying to use the values obtained through the user form in your PHP code.

How do you fix an undefined index?

To resolve undefined index error, we make use of a function called isset() function in PHP. To ignore the undefined index error, we update the option error_reporting to ~E_NOTICE to disable the notice reporting.

How does PHP handle undefined index error?

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.

How check variable is undefined in PHP?

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.


2 Answers

Yes, the undefined index only triggers for not null variables (don't ask me why). This will trigger a notice though:

<?php
    error_reporting(E_ALL);
    $myArray = array();
    echo $myArray['foo']['bar'];
?>
like image 59
Madara's Ghost Avatar answered Sep 26 '22 13:09

Madara's Ghost


no, it doesn't show any error when $myArray is set to null. if it is an empty array or any other value except for null then it returns a E_NOTICE level error. i actualy don't know why but it is as it is.

like image 39
FabioG Avatar answered Sep 24 '22 13:09

FabioG