NYCPHP Meetup

NYPHP.org

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

Kenneth Downs ken at secdat.com
Mon Aug 18 08:51:29 EDT 2008


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');


>  NULL
>
> Is it ok to access non-existent array elements?
>
> Will accessing an array element using a key that does not exist always
> return NULL?
>
> Mike
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>   


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




More information about the talk mailing list