By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,977 Members | 1,352 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,977 IT Pros & Developers. It's quick & easy.

isset returns true when it should return false

P: n/a
<?php
$var['a'] = 'test';

echo isset($var['a']['b']) ? 'true' : 'false';
echo '<br>';
echo isset($var['b']) ? 'true' : 'false';
?>

Why does that result in this output?:

true
false

It seems to me that it should instead output this:

false
false

Using array_key_exists instead works, but I'm not sure why isset
doesn't? Is this maybe a PHP bug?

Apr 27 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 27.04.2007 21:01 yawnmoth wrote:
<?php
$var['a'] = 'test';

echo isset($var['a']['b']) ? 'true' : 'false';
Since $var['a'] is string, php applies string indexing operator, which
converts its second argument to an integer. That is, $var['a']['b']
becomes $var['a'][0] and equals to "t", which is, of course, set.

--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
Apr 27 '07 #2

P: n/a
yawnmoth kirjoitti:
<?php
$var['a'] = 'test';

echo isset($var['a']['b']) ? 'true' : 'false';
echo '<br>';
echo isset($var['b']) ? 'true' : 'false';
?>

Why does that result in this output?:

true
false

It seems to me that it should instead output this:

false
false
It has something to do with the fact that $var['a'] is a string and
strings can be handled as an array of characters. I only assume php
casts any non-integer offsets to integers since strings (when handled as
an array of characters) is non-associative. Thus 'b' is cast to int,
which is zero. var_dump($var['a']['b']) echoes 't' which is the first
character in 'test', which supports the theory that 'b' is being casted
to int.

Also, if you use an integer instead of string:
$var['a'] = 7;
echo isset($var['a']['b']) ? 'true' : 'false';
it yields false now, since an integer is not an array.
Using array_key_exists instead works, but I'm not sure why isset
doesn't? Is this maybe a PHP bug?
A bug or a feature? That's a tricky question. I suppose this is
undocumented feature. The string accessing with [] is explained in the
manual, but it does not mention the automatic casting.

The workaround:
echo (is_array($var['a']) && isset($var['a']['b'])) ? 'true' : 'false';

Make sure you are dealing with an array, because the results of isset
are ambiguous when it's a string.

--
Ra*********@gmail.com

"Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze
Apr 27 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.