Jump to content


Photo

Check for existence of key in nested array


  • Please log in to reply
3 replies to this topic

#1 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 21 April 2006 - 11:01 PM

So, i have an array...


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


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


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

}


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



#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,018 posts

Posted 22 April 2006 - 09:54 AM

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

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

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";

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 24 April 2006 - 03:13 PM

Ahhh! ok....this is perfect...one question. what does the ampersand in "&$arr" accomplish?

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,018 posts

Posted 24 April 2006 - 06:01 PM

[!--quoteo(post=368012:date=Apr 24 2006, 04:13 PM:name=bcamp1973)--][div class=\'quotetop\']QUOTE(bcamp1973 @ Apr 24 2006, 04:13 PM) View Post[/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.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users