[Solved] What does array_diff_uassoc() function do in php?


The comparison function allows you to create custom logic to determine whether the two entries are the same or not.

The keys in these two arrays look totally different, because they are in different languages.

$data1 = [
  'red' => true,
  'yellow' => true,
  'green' => true,
  'blue' => true,
  'black' => true,
];

$data2 = [
  'rouge' => true,
  'jaune' => true,
  'bleu' => true,
  'vert' => true,
  'blanc' => true,
];

But we can still do a diff against them using a custom comparison function that recognises where the two languages have equivalent values

function colourLanguageTest($a, $b) {
    static $comparator = [
        'red' => 'rouge',
        'yellow' => 'jaune',
        'green' => 'vert',
        'blue' => 'bleu',
        'black' => 'noir',
        'white' => 'blanc',
    ];

    if (isset($comparator[$a])) {
        return $comparator[$a] != $b;
    } elseif(isset($comparator[$b])) {
        return $comparator[$b] != $a; 
    }

    return true;
}

$result = array_diff_uassoc($data1, $data2, 'colourLanguageTest');

var_dump($result);

The comparison function checks for the entries in the comparator table, so it can identify that red and rouge are the same, and treat them as a match. A boolean false (0) will be returned if there is a match a boolean true (1) if there is no match.
Because this is a diff function, it filters out all entries from the first array where our custom logic returns 0 (indicating a match) and leaves only entries where our comparison logic doesn’t return a 0 (ie returns 1 or -1 or 999 or -23456)

Because ‘red’, ‘yellow’, ‘green’ and ‘blue’ all have corresponding entries in the second array that match according to the language lookup, only ‘black’ doesn’t have a corresponding entry in the second data array, so the result of our call to array_diff_uassoc() returns

array(1) {
  ["black"]=>
  bool(true)
}

2

solved What does array_diff_uassoc() function do in php?