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
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 .
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.
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 )
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With