2

How do I check to see if a compound key exists with array_key_exists such as

$myarr['ind1']['ind2']

Would like to see if the key ['ind1']['ind2'] exists in $myarr.

I googled this and looked at some similar answers but couldn't find anything.

macmiller
  • 325
  • 1
  • 4
  • 15

2 Answers2

4
if(array_key_exists("ind1", $myarr) && array_key_exists("ind2",$myarr["ind1"])) {

}
Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

You can make use of issetDocs to check for an array member that not equals NULL, which is the case for a compound array and safe to assume in your case:

if (isset($myarr['ind1']) && array_key_exists('ind2', $myarr['ind1'])
{
   ...
}

If $myarr['ind2'] potentially never equals to NULL you can do the following, which might show better what you're trying to check:

if (isset($myarr['ind1']['ind2']))
{
   ...
}

This checks the compound key does exists and is not NULL.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • yes, it seems like isset check is the easiest way to get what I am after. thought this would return an error if the keys didn't exist but it doesn't. thx – macmiller Aug 25 '11 at 09:56