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.

+3


source to share


3 answers


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

      

+1


source


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

,

doc link

+2


source


$array_new1  = explode(',',$array1);
$array_new2  = explode(',',$array2);

    $array_1 = array_map('trim', $array_new1);
    $array_2 = array_map('trim', $array_new2);

$data =array();
 foreach($array_2 as $value){ 
     if(in_array($value,$array_1)){    
       $data[] = $value; 
     } 
 }
  echo count($data);

      

+2


source







All Articles