Mass matches array_intersection in two arrays

I have 2 arrays:

$array1 = array("dog","cat","butterfly")
$array2 = array("dogs","cat","bird","cows")

I need to get all partial matches from $ array2 compared to $ array1, for example:

array("dog","cat")

Therefore, I need to check if there are partial matches of words in $ array2 and output a new array using the keys and values ​​of $ array1.

array_intersection prints only complete matches

thank

+4
source share
2 answers

Another way to get the same result

<?php

   $array1 = array("dog","cat","butterfly");
   $array2 = array("dogs","cat","bird","cows");

   // Array output will be displayed from this array
   $result_array = $array1;

   // Array values are compared with each values of above array
   $search_array = $array2;


   print_r( array_filter($result_array, function($e) use ($search_array) {
       return preg_grep("/$e/",$search_array);
   }));

?>

Output

[akshay@localhost tmp]$ php test.php 
Array
(
    [0] => dog
    [1] => cat
)
+1
source

Try it,

$array1 = array("dog","cat","butterfly");
$array2 = array("dogs","cat","bird","cows");

function partial_intersection($a,$b){
    $result = array();
    foreach($a as $v){
        foreach($b as $val){
            if( strstr($val,$v) || strstr($v,$val) ){ $result[] = $v; }
        }
    }
    return $result;
}

print_r(partial_intersection($array1,$array2));
+2
source

All Articles