Dan W.
Dan W.

Reputation: 61

Undefined Index Behavior

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?

Upvotes: 5

Views: 314

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 175088

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'];
?>

Upvotes: 3

FabioG
FabioG

Reputation: 2986

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.

Upvotes: 2

Related Questions