PHP two arrays compare

Viewed 56

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. Any advise please. Need to loop twice?

2 Answers

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

If you change the $array2 with keys, so you can check if the key exists in the array. When you check the key, it is exact. When you check for lemon, the waterlemon will not come up, else you have to check for that exception.

You could do something like this:

$array1 = ["apple", "banana", "grape", "watermelon"];

$array2 = [
    'apple' => "there is apple", 
    'banana' => "there is banana", 
    'lemon' => "there is lemon",
    //...
];

$result = [];
foreach ($array1 as $value) {
   if (isset($array2[$value])) {
      $result[] = $array2[$value];
   }
}

print_r($result);
Related