Reputation: 117
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 like so:
array("dog","cat")
So I need to check if there are partial word matches in $array2 and output new array with $array1 keys and values.
array_intersection
only outputs full matches
Thanks
Upvotes: 4
Views: 85
Reputation: 21422
Try this,
$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));
Upvotes: 2
Reputation: 16997
Some more 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
)
Upvotes: 1