Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To compare two arrays while considering duplicate value

Tags:

php

i have two arrays

$array1 = array(1, 2,  2, 3);
$array2 = array( 1, 2,  3,4);

and when did :

var_dump(array_diff($array1, $array2));

getting :

array(0){}

as output , but i am looking for :

array(1){[2]=>2}

can someone please let me know how to do it

Thanks in Advance

like image 950
user522170 Avatar asked Oct 29 '12 12:10

user522170


People also ask

How do you compare two arrays to delete duplicates?

Example 1: Using concat() and for Loop In the above program, the two array elements are merged together and the duplicate elements are removed. Here, The two arrays are merged using the concat() method. The for...of loop is used to loop through all the elements of arr .

How do you compare two values in an array?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.


2 Answers

Try this

$array1 = array(1, 2, 2, 3, 4, 5, 5, 7);
$array2 = array(1, 2, 4, 6, 3, 3, 5);
$diff = array_filter($array1, 
  function ($val) use (&$array2) { 
    $key = array_search($val, $array2);
    if ( $key === false ) return true;
    unset($array2[$key]);
    return false;
  }
);
print_r($diff);
// Array ( [2] => 2 [6] => 5 [7] => 7 )
like image 170
air4x Avatar answered Oct 20 '22 00:10

air4x


If you want to count number of duplicate element from same array as well as from multiple arrays, please use below code,

<?php
    $array1 = array(1,2,2,3,7);
    $array2 = array(1,2,3,4);
    $diff_array = array();

    $diff_array1 = array_count_values($array1);
    $diff_array2 = array_count_values($array2);

    $a = array_keys($diff_array1);
    $b = array_keys($diff_array2);

    for($i=0;$i<count($a);$i++)
    {
        if($a[$i] == $b[$i])
        {
            $x = $a[$i];
            $y = $b[$i];
            $diff_array1[$x] += $diff_array2[$y];
        }
    } 
    $diff_array1=array_diff($diff_array1, array('1'));
    echo '<pre>';
    print_r($diff_array1);
?>
like image 34
Crazy4Php Avatar answered Oct 20 '22 00:10

Crazy4Php