Array Functions

PHP array_udiff() Function

Topic: PHP Array ReferencePrev|Next


The array_udiff() function compares the values of two or more arrays and returns the differences using a user-defined value comparison function.

This is unlike array_diff() which uses an internal function for comparing the values.

The following table summarizes the technical details of this function.

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


The basic syntax of the array_udiff() function is given with:

array_udiff(array1, array2, ..., value_compare_function);

The following example shows the array_udiff() function in action.

// Define value Comparison function
function compare($a, $b){
    // Converting value to lowercase
    $a = strtolower($a);
    $b = strtolower($b);

    if($a == $b){
        return 0;
    return ($a < $b) ? -1 : 1;

// Sample arrays
$array1 = array("apple", "ball", "cat", "dog", "elephant");
$array2 = array("alligator", "DOG", "elephant", "lion", "Cat");

// Computing the difference
$result = array_udiff($array1, $array2, "compare");

Note: The value comparison function must return an integer equal to zero if both values are equal, an integer less than zero if the first value is less than the second value, and an integer greater than zero if the first value is greater than the second value.


The array_udiff() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array to compare from.
array2 Required. Specifies an array to compare against.
... Optional. Specifies more arrays to compare against.
value_compare_function Required. Specifies a callback function to use for value comparison.

More Examples

Here're some more examples showing how array_udiff() function actually works:

The following example shows how to compare the values of three arrays and get the differences using the PHP's built-in strcasecmp() function as value comparison function.

// Sample arrays
$array1 = array("apple", "ball", "cat", "dog");
$array2 = array("Cat", "Lion", "Tiger");
$array3 = array("APPLE", "BANANA");

// Computing the difference
$result = array_udiff($array1, $array2, $array3, "strcasecmp");

You can also use associative arrays, however the keys are not considered in the comparison.

// Sample arrays
$array1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$array2 = array("x"=>"black", "y"=>"BLUE", "z"=>"Red");

// Computing the difference
$result = array_udiff($array1, $array2, "strcasecmp");
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties