phparraysfilterintersectpartial-matches

Keep values in a flat array if they contain a value from another flat array as a substring


There are two arrays.

$array1 = ["apple", "banana", "grape", "watermelon", "taro", "coffee", "green tea", "tomato", "cabbage"];
$array2 = ["there is apple", "there is banana", "there is lemon", "there is melon", "there is cucumber"];

result I want is

$array2 = ["there is apple", "there is banana"]; 

Logic is check array2 contains any value from array1.

I can do it with a string and one array

$string = "apple";
$array = ["there is apple", "there is banana", "there is lemon", "there is melon", "there is cucumber"];

with two arrays quite hard.

Do I need to loop twice?


Solution

  • You only need to loop once:

    $array = ["apple", "banana", "grape", "watermelon"];
    $array2 = ["there is apple", "there is banana", "there is lemon", "there is melon", "there is cucumber"];
    
    foreach($array as $k=>$v){
       if(isset($array2[$k]) && strstr($array2[$k], $v)){
           $result[] = $array2[$k];
       }
    }
    
    print_r($result); // Array ( [0] => there is apple [1] => there is banana )
    

    See Demo

    Also take a look at strstr()