Vitor Villar
Vitor Villar

Reputation: 1925

Accessing boolean var as array in PHP return NULL

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?

Upvotes: 1

Views: 208

Answers (3)

Răducanu Ionuţ
Răducanu Ionuţ

Reputation: 430

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

Try this

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47274

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.

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

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.

Upvotes: 4

Related Questions