Jump to content

Archived

This topic is now archived and is closed to further replies.

bcamp1973

Check for existence of key in nested array

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...

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
Ahhh! ok....this is perfect...one question. what does the ampersand in "&$arr" accomplish?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

×

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.