Sam
Sam

Reputation: 81

Find One Array Element Data In Other Array Element

My question is related to PHP

I have 2 arrays:

Array1 
(
    [0] => "Pecan, Blackberry, Peach, Apple, Orange, Banana"
    [1] => "Potato, Tomato, Broccoli, Spinach"
    [2] => "Cake, Ice-cream, Candy, Jelly, Chocolate"
}

Array2 
(
    [0] => "Banana"
    [1] => "Apple"
    [2] => "Peach"
}

and I only want to match Array2[0] element with Array1[0] to check whether the value of Array2[0] (in this case, it is Banana) exists in the element of Array1[0] or not

Though, I can work around this with someway, but I'd like to know if there's a fast, less memory consuming built-in function or another way because I need to do this 10 times when my page loads.

Upvotes: 0

Views: 74

Answers (2)

Glavić
Glavić

Reputation: 43552

This will find exact value (Bananaaaaa is not same as Banana).

Code

foreach ($array2 as $key => $val) {
    if (in_array($val, explode(', ', $array1[$key]))) {
        var_dump("$val is found in \$array1[$key]");
    } else {
        var_dump("$val is not found in \$array1[$key]");
    }
}

Output

string(29) "Banana is found in $array1[0]"
string(32) "Apple is not found in $array1[1]"
string(32) "Peach is not found in $array1[2]"

Upvotes: 0

scottlimmer
scottlimmer

Reputation: 2268

If I understand your question correctly, this should be what you're after:

foreach ($array2 as $key => val) {
    if (stripos($array1[$key], $val) !== false) {
        // match
    }
}

Upvotes: 1

Related Questions