PHP array_udiff_assoc() Function


Definition and Usage

The array_udiff_assoc() function compares the values of two or more arrays, and returns the differences. This function compares the values of two or more arrays, and returns an array containing the elements from the first array that are not present in any of the other arrays.

Note: This function uses a user-defined function to compare the values. This function compares the values by their keys and values.

Syntax

array_udiff_assoc(array1, array2, array3..., myfunction)

Parameter List

Parameter Description
array1 Required. The array to compare from.
array2 Required. An array to compare against.
array3 Optional. An array to compare against.
myfunction Required. A string that calls back the comparison function. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered respectively less than, equal to, or greater than the second.

Technical Details

Return Value: Returns an array containing the elements from the first array that are not present in any of the other arrays.
PHP Version: PHP 5+

Examples

Example 1

Compare the values of two arrays and return the differences:

Code:

<?php
function myfunction($a,$b)
{
if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}

$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","yellow","b"=>"green");

$result=array_udiff_assoc($a1,$a2,"myfunction");
print_r($result);
?>

Output:

Array
(
     => green
     => blue
)

Example 2

Compare with three arrays:

Code:

<?php
function myfunction($a,$b)
{
if ($a===$b)
  {
  return 0;
  }
  return ($a>$b)?1:-1;
}

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","yellow","b"=>"green");
$a3=array("e"=>"red","f"=>"green","c"=>"blue");

$result=array_udiff_assoc($a1,$a2,$a3,"myfunction");
print_r($result);
?>

Output:

Array
(
     => yellow
)