NYCPHP Meetup

NYPHP.org

[nycphp-talk] Accessing non-existent array elements ok?

Kenneth Downs ken at secdat.com
Mon Aug 18 11:36:14 EDT 2008


Michael B Allen wrote:
> On Mon, Aug 18, 2008 at 8:51 AM, Kenneth Downs <ken at secdat.com> wrote:
>   
>> Michael B Allen wrote:
>>     
>>> I seem to recall getting a warning trying to access array elements
>>> that did not exist but I can't seem to trigger that issue right now.
>>>
>>> The following code:
>>>
>>>  <?php
>>>  $a = array('a' => 'b');
>>>  $result = $a['c'];
>>>  var_dump($result);
>>>
>>> yields the following:
>>>
>>>  $ php -f t.php
>>>
>>>       
>> Michael, I found the following routine to be very useful dealing with
>> arrays:
>>
>> function a(&$array, $key,$default='') {
>>  if (isset($array[$key])) return $array[$key];
>>  else return $default;
>> }
>>
>> This allows you to code up simpler unconditional routines with code like:
>>
>> $value = a($myArray,$key,'AccetableDefault');
>>     
>
> That's pretty much what I'm doing right now:
>
>   function _array_val($a, $k, $d = null) {
>       if (is_array($a) && array_key_exists($k, $a))
>           return $a[$k];
>       if (func_num_args() == 3)
>           return $d;
>       throw new Exception("No such array key: $k");
>   }
>
> I was just hoping to streamline things further.
>   

Michael, there is a significant difference in our two routines, which 
probably reflects a different approach.  My approach is to make sure 
that the array access always returns a usable value, even if the array 
element does not exist.  This is why my routine does not throw an 
exception or return null.  Using this routine presupposes a broader 
approach in which the calling routine "knows" an acceptable default that 
it passes to the array access.  This default can be pulled from a 
configuration system in the best case, but many times it is perfectly 
acceptable to use defined constants to provide the default. 



> Thanks,
> Mike
>
>   


-- 
Kenneth Downs
Secure Data Software, Inc.
www.secdat.com    www.andromeda-project.org
631-689-7200   Fax: 631-689-0527
cell: 631-379-0010

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20080818/76247de2/attachment.html>


More information about the talk mailing list