This is a discussion on isset returns true when it should return false within the PHP Language forums, part of the PHP Programming Forums category; <?php $var['a'] = 'test'; echo isset($var['a']['b']) ? 'true' : 'false'; echo '<br>'; echo isset($var['b']) ? '...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
<?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? |
|
|||
|
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 |
|
|||
|
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. -- Rami.Elomaa@gmail.com "Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze |