Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isset() returns true from a string variable accessed as an array with any key

Tags:

php

I face a problem like this:

$area="Dhaka";

isset($area); //returns true which is OK

isset($area['division']); //returns true why?

// actually, any array key of area returns true

isset($area['ANY_KEY']);//this is my question 1

isset($area['division']['zilla');//now it returns false. 

//as I know it should returns false but why previous one was true.

Now if I do this:

$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this

isset($area['division']['ANY_KEY']); // returns true why? question #2

Basically both of my questions are the same.

Can anyone explain this?

like image 686
Shaiful Islam Avatar asked Jan 07 '15 19:01

Shaiful Islam


2 Answers

As with every programming language in existence, a string is stored as an array of characters.

If I did:

$area = "Dhaka";
echo $area[0];

It would return D.

I could also echo the whole string by doing:

echo $area[0].$area[1].$area[2].$area[3].$area[4];

PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.

So by doing:

echo $area['division'];

You would essentially be doing:

echo $area[0];

and again, getting D.

That's why isset($area['division']) returns a true value.

Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.

The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:

is_array($area) && isset($area['division'])
like image 105
sjagr Avatar answered Nov 02 '22 07:11

sjagr


PHP lets you treat a string as an array:

$foo = 'bar';
echo $foo[1]; // outputs 'a'

So

$area['division']

will be parsed/executed as

$area[0];

(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.

like image 23
Marc B Avatar answered Nov 02 '22 06:11

Marc B