NYCPHP Meetup

NYPHP.org

[nycphp-talk] Handling empty values in hashes

David Krings ramons at gmx.net
Thu Jul 17 15:51:54 EDT 2008


Daniel Convissor wrote:
> Paul:
> 
>> $value=$array[$key]
> 
> One right way to do this is:
> 
> if (array_key_exists($key, $array)) {
>    // Life is good.
>    $value = $array[$key];
> } else {
>    // Erm, it doesn't exist.  Now what?
>    // Typically either set to NULL or throw error.
> }
> 
> --Dan
> 


I second that. From a professional QA view point I way too often see that 
developers assume something to be there even if it is a record that their own 
code wrote to a table or array just a second earlier. While that may pan out 
most of the time and not cause problems all pieces come off once there is a 
problem.
I use mainly isset() since that allows for crafting the whole checking and 
default value assignment in one line that is still readable.

I find this to be similar to initializing variables. Sure, under PHP you can 
get away with not doing that, but once you come across the problem where you 
think $i has the value of 1 when PHP really sets it to 0 you get to understand 
why other languages/compilers throw errors when a variable gets used and comes 
out of nowhere. In that sense I find it quite OK that warnings or errors get 
thrown when one requests the value from an array element, but the provided key 
is nowhere to be found.

David



More information about the talk mailing list