Tell me how many elements are the same in 2 arrays?
Is there a way in PHP and MySQL to be able to compare two different array (list) variables and say how many elements are the same
For example,
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
Then the echo expression will indicate how many elements are the same. In this example it will be 2 and it will be reflected.
This differs from most of the array questions because of the way my site is set up with commas, which can make it quite complex.
First you need to convert the string to a trimmed array. Then use
array_intersect
to get the overall values.
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
$array_new1 = array_map('trim', explode(',', $array1));
$array_new2 =array_map('trim', explode(',', $array2));
$common = array_intersect($array_new1, $array_new2);
print_r($common);
echo count($common);
source to share
Try the array_intersect()
function in php
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r(count($result));
?>
You can count the elements in the output array using the function count()
,
source to share