4

Why does PHP throw a "Notice: Undefined offset" error here:

<?php
$MyVar = array();
echo $MyVar[0]; //Notice: Undefined offset: 0
?>

But not here:

<?php
$MyVar = false;
echo $MyVar[0]; //No error
?>
4
  • 1
    It is due to the variable type. Since an array has an offset, but a boolean value does not, an offset is not undefined, instead it is simply NULL. The same offset notice applies to strings $MyVar = ''; echo $MyVar[0]; Which would result in Uninitialized string offset: 0 Commented Jun 6, 2017 at 18:42
  • @fyrye me attempting to reference an offset of a boolean should be even more of a reason to throw an error/warning/notice Commented Jun 6, 2017 at 18:45
  • See: php.net/manual/en/language.types.string.php#example-55 Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. This implies that PHP expects you to verify the variable type prior to accessing it with [] or {} e.g. if (is_array($MyVar)) Commented Jun 6, 2017 at 18:52
  • @fyrye put that in an answer and I'll mark it as accepted Commented Jun 6, 2017 at 18:58

2 Answers 2

0

It's ultimately because in your 2nd example $MyVar[0] is null which isn't an error. You could probably reference $MyVar[0][1][2][3] and get the same result.

The first example isn't null it's a missing index in an array so it warns you.

Sign up to request clarification or add additional context in comments.

2 Comments

The first example does in fact echo NULL, but also throws an error. Try the first example and you'll see "Notice: Undefined offset" followed by "NULL"
That does make sense as PHP specifically looks out for undefined indexes. Note it's not an error but a notice.
0

Undefined offset is provided when there are no values in an array and you're trying to reference an uninitialised index.

In case of the 2nd code, you've assigned(initialised) a value to the variable which is not different from variable[0].

If you assign values for 1st two indexes in 1st example, and refer to the 3rd index, you should get the undefined offset error.

I dont think it is about null or not, but a case of assigning values to indexes. If you take a C parlance, array is an equivalent of malloc(upto a certain extent). Thankfully PHP does not crash, just throws an undefined index[offset] error

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.