Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Say how many items are the same in 2 arrays?

Tags:

arrays

php

mysql

Is there a way within PHP and MySQL to be able to compare 2 different array (list) variables and say how many items are the same

For example,

$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";

Then an echo statement would say how many items are the same. In this example, it would be 2 and this would be echoed.

This is different to most array questions because of the way my site is set up using commas which can make it quite complicated


2 Answers

Try 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 elements in the output array using count() function,

doc link

like image 118
Shobi Avatar answered Jan 22 '26 16:01

Shobi


$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);
like image 27
harsh kumar Avatar answered Jan 22 '26 16:01

harsh kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!