Jump to content

Check for existence of key in nested array


bcamp1973

Recommended Posts

So, i have an array...

[code]

$arr = array(
   'foo' => array('yada','yo','bing'),
   'bar' => array('keep','it','simple','stupid')
);

[/code]

and i want to check for the existence of a key in one of the nested arrays so i'm doing this...

[code]

$var1 = 'bar';
$var2 = 'simple';

if(isset($arr[$var1][$var2])) {

   echo '<p>Yup. Key '.$var2.' is in array '.$var1.'</p>';

} else {

   echo '<p>nope, nada, zilch...it's just not there</p>';

}

[/code]

Even when i put in values that are correct, i'm still getting my error message. Am i doing something wrong here? I don't get it...

Link to comment
Share on other sites

"simple" isn't a key, it's a value.

It's key is $arr['bar'][2]

[code]Try
$arr = array(
   'foo' => array('yada','yo','bing'),
   'bar' => array('keep','it','simple','stupid')
);

function inMyArray ($srch, &$arr) {
         foreach ($arr as $subarr) {
                  if (in_array($srch, $subarr)) {
                      return true;
                  }
         }
         return false;
}

$s = 'simple';

echo inMyArray($s, $arr) ? "found" : "not found";[/code]
Link to comment
Share on other sites

[!--quoteo(post=368012:date=Apr 24 2006, 04:13 PM:name=bcamp1973)--][div class=\'quotetop\']QUOTE(bcamp1973 @ Apr 24 2006, 04:13 PM) [snapback]368012[/snapback][/div][div class=\'quotemain\'][!--quotec--]
...one question. what does the ampersand in "&$arr" accomplish?
[/quote]

It passes the original array "by reference" instead of creating a copy of the array and passing that copy to the function.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.