You are here: Re: isset returns true when it should return false « PHP Programming Language « IT news, forums, messages
Re: isset returns true when it should return false

Posted by Rami Elomaa on 04/27/07 19:33

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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация