Find all the differences in arrays

I have two arrays:

$array1 = array('red', 'blue', 'green', 'yellow');

$array2 = array('red', 'blue', 'green', 'yellow', 'blue', 'black');

I want to know the differences between them.

array_diff() can be used to tell me that black only appears in the second array

array_unique()will only show unique values ​​/ deletes duplicate values, but does not tell me that the value bluewas deleted due to uniqueness.

Is there a function to tell me the duplicate value in the second array ( blue)?

+3
source share
5 answers

No, but you can use the one I wrote below:

<?php
// function
function dupes_in_array($array){
  if(!is_array($array)) return 0; // check, if $array is an array
  $arr = array_count_values($array);
  foreach($arr as $key => $val) { if($val > 1) $duplicates[] = $key; }
  return $duplicates;
}

// demonstration
$array = array('red', 'blue', 'green', 'yellow', 'blue', 'black', 'green');
$dupes = dupes_in_array($array);
echo "Duplicate values: ";
var_dump($dupes);

?>

Conclusion:

Duplicate values: array(2) { [0]=> string(4) "blue" [1]=> string(5) "green" }

Note: the output is blue and green, because the input array has both of them as duplicates.

If $val- > 1, then we have a duplicate.

: array_count_values

+2

$result = array_filter(array_count_values($array2), function ($val) {
    return $val > 1;
});

$duplicates = array_keys($result);

:

Array
(
    [0] => blue
)

-

+2

, array_diff_assoc :

php > $a1 = array('red', 'blue', 'green', 'yellow', 'blue', 'black');
php > $a2 = array('red', 'blue', 'green', 'yellow');
php > var_dump(array_diff_assoc($a1,$a2));
array(2) {
  [4]=>
  string(4) "blue"
  [5]=>
  string(5) "black"
}
+1
source

I can also add my solution to the mix:

<?php

    $r1 = ["red","blue","green","yellow"];
    $r2 = ["red","blue","green","yellow","blue","black"];

    $diff = array_diff($r2,$r1);
    $dupe = array_keys(array_filter(array_count_values($r2), function ($val){
                        return $val > 1;}));

    var_dump(array_merge($diff,$dupe));

?>

Conclusion:

array(2) {
  [0]=>
  string(5) "black"
  [1]=>
  string(4) "blue"
}
+1
source

You can get the difference by comparing $array2with array_unique($array2)as follows:

print_r(array_diff_assoc($array2, array_unique($array2)));

Conclusion:

Array
(
    [4] => blue
)

This is not the most efficient, but it has the advantage of knowing the duplicate index.

+1
source

All Articles