Re: Mystery foreach error

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2013/3/14 David Harkness <david.h@xxxxxxxxxxxxxxxxx>

> On Wed, Mar 13, 2013 at 4:44 PM, Angela Barone
> <angela@xxxxxxxxxxxxxxxxxxxx>wrote:
>
> > I ran across if(array_key_exists) and it seems to work.  How does that
> > differ from if(isset($states[$state]))?
>
>
> Hi Angela,
>
> isset() will return false for an array key 'foo' mapped to a null value
> whereas array_key_exists() will return true. The latter asks "Is this key
> in the array?" whereas isset() adds "and is its value not null?" While
> isset() is every-so-slightly faster, this should not be a concern. Use
> whichever makes sense for the context here. Since you don't stick null
> values into the array, I prefer the isset() form because the syntax reads
> better to me.
>

Just a minor addition: Because 'null' is the representation of "nothing"
array_key_exists() and isset() can be treated as semantically equivalent.

Another approach (in my eyes the cleaner one ;)) is to simply _ensure_ that
the keys I want to use exists. Of course this only works in cases, where
the key is not dynamical, or the dynamic keys are known, which is not the
case here, it seems.

$defaults = array('stateNames' => array(), 'states' => array());
$values = array_merge($defaults, $values);
$values['states'] = array_merge(array_fill_keys($values['stateNames'],
null), $values['states']);
if (!$values[$myState]) {

}


>
> Peace,
> David
>



-- 
github.com/KingCrunch

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux