user5434892
user5434892

Reputation:

Array search in PHP with duplicate value

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.

Upvotes: 1

Views: 32

Answers (3)

Jordy García
Jordy García

Reputation: 141

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

Upvotes: 2

Abhishek
Abhishek

Reputation: 1068

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

?>

Upvotes: 0

SEoF
SEoF

Reputation: 1114

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

Upvotes: 0

Related Questions