1

I'm trying to get the key of a subarray based on a value in that subarray. So, based on the example below, how can I return the key of the array containing 'apple'?

Array ( 
    [0] => Array ( 
        [fruit] => apple 
        [colour] => green 
    ) 
    [1] => Array ( 
        [fruit] => banana 
        [colour] => yellow 
    ) 
)

So logically, something like:

if ('apple' is in $subarray) {
    echo $subarray_key;
}

Thanks in advance.

1
  • You have to use a loop to check all the values. Commented Sep 26, 2014 at 1:03

2 Answers 2

4

Assuming that your array is stored in $arr variable, you can do

foreach($arr as $key => $value){
    if(in_array('apple',$value){
        echo $key;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

a closing bracket (for the if) is missing.. foreach($arr as $key => $value){ if(in_array('apple',$value) ) { echo $key; } }
2
 foreach($array as $key => $val){
      if($val == 'apple'){
           print $key;
      }
 }

You can use array keys and do some other stuff but for the most part you're going to end up just iterating through the array anyways

1 Comment

I guess $val will be an array which contains the value 'apple' not the value itself

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.