0

I have the following setup where I'm trying to use an array of array structure. I'm not sure how to get the key value once the value is found in the array of arrays.

$testboat = 'smallest boat';
$allboats = array(40=>array(1=>'big boat',
                            2=>'bigger boat'
                      ),
                  30=>array(1=>'little boat',
                           2=>'tiny boat',
                           3=>'smallest boat'));

foreach($allboats as $boats){
    foreach($boats as $boat){
       if($testboat == $boat) {

       /*looking to echo the key or value 30; */

      }  

   }
}
2
  • 6
    foreach ($boats as $key => $boat) would be a start. Commented Dec 14, 2016 at 21:21
  • thanks but I find that's the wrong place to start. foreach($allboats as $key =>$boats) provides the correct place. Commented Dec 14, 2016 at 21:33

3 Answers 3

1

Use the $key => $value syntax of foreach(). Also, no need to loop through the inner arrays:

foreach($allboats as $key => $boats){
    if(in_array($testboat, $boats)) {
        echo $key;
        break; //if you want to stop after found
    }
}

If you want to get the outer key and the inner key:

foreach($allboats as $key => $boats){
    if(($inner_key = array_search($testboat, $boats)) !== false) {
        echo "$key and $inner_key";
        break; //if you want to stop after found
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

can i know what for the !== false??
@FullStack Strict not equal to false, because array_search can return 0 as a key which would loosely evaluate to false.
0
$testboat = 'smallest boat';
$allboats = array(40=>array(1=>'big boat',
                            2=>'bigger boat'
                      ),
                  30=>array(1=>'little boat',
                           2=>'tiny boat',
                           3=>'smallest boat'));

foreach($allboats as $id => $boats){
    //$id will be 40, then 30
    foreach($boats as $id2 => $boat){
        //$id2 will be 1,2...
       if($testboat == $boat) {
       echo $id . '-' . $id2;
       /*looking to echo the key or value 30; */

      }  
   }
}

Comments

0

You'd have to do the following:

foreach($allboats as key1 => $boats){
    foreach($boats as key2 => $boat){

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.