1

discussing with a friend of my work, we discover something weird about PHP. Let's get the following code:

<?php

$leo = false;
$retorno = $leo[0];
var_dump($retorno);

The return of var_dump() is NULL. Now, the thing is, why is returning NULL, if we are trying to access a bool as array?

The correct behavior isn't throw an exception telling us, that we are trying to access a non-array object as array (in this case a boolean var)?

what you guys think about that?

2
  • Until PHP 5.4, if you tried to get a string index of a string, it would cast the string to 0 and get the first letter of the word, i.e. $s = 'asdf'; echo $s['f'];. Now it will give you a warning saying that the offset does not exist. Commented Jun 12, 2015 at 18:11
  • So where are we with this question? Commented Jun 12, 2015 at 19:51

3 Answers 3

4

Since you are trying to access not a string, but a boolean it returns NULL. As from the manual:

Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

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

Comments

0

It's NULL because $leo[0] isn't $leo. You haven't assigned the bool or string to $leo[0], therefore it's empty, and ultimately results in being NULL.

If you were to put:

$retorno = $leo;

Or

$leo[0] = false;

Then you would get the result you are expecting.

Comments

0
$leo = false;
$retorno = array($leo);
var_dump($retorno[0]);

Try this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.