1

I have this array:

$myFruit = 'apple';
$fruits = array( 
    '0' => array('banana', 'cherry'),
    '1' => array('apple', 'pear'),
    '2' => array('apple', 'kiwi')
);

I want to know in which array apple is.

So my code is the following and it's working.

foreach($fruits as $key => $fruit) {;
    if(in_array($myFruit, $fruit)) {
        echo $key;
    }
}

My problem is actually apple is in two arrays (1 and 2) and the code echoes 12 whereas it should stop when one result was found.

So it should echo 1 only and stop searching after.

How can I change my code for this ?

Thanks.

1
  • 1
    you can use break statement after echo $key Commented Nov 23, 2017 at 20:47

3 Answers 3

2

Just add a break in your foreach to make it returns the first array where your word was found.

foreach($fruits as $key => $fruit) {;
   if(in_array($myFruit, $fruit)) {
       echo $key;
       break;
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

sure about this $break I don't think break is a variable. :) it's a language construct...
You're right I add an "$" that it doesn't need, corrected.
0

Try using a function, and a return statement in that function.

function search_subarray($haystacks, $needle) {
    foreach($haystacks as $key => $value) {
        if(in_array($needle, $value)) {
            return $key;
        }
    }
}

search_subarray($fruits, $fruit);

Comments

0

Using break statement will do the work.

You can read about it on official website break

<?php

$myFruit = 'apple';
$fruits = array( 
    '0' => array('banana', 'cherry'),
    '1' => array('apple', 'pear'),
    '2' => array('apple', 'kiwi')
);

foreach($fruits as $key => $fruit) {;
    if(in_array($myFruit, $fruit)) {
        echo $key;
        break;// THIS WILL BREAK THE FOREACH LOOP
    }
}

?>

Comments

Your Answer

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