array_udiff()

array_udiff() — Computes the difference of arrays by using a callback function for data comparison.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data.

Signature

array_udiff(array $array, array ...$arrays, callable $value_compare_func): array callback(mixed $a, mixed $b): int

Parameters

ParameterTypeWhat it takes
$arrayarrayThe first array.
...$arraysarrayArrays to compare against.
$value_compare_funccallableThe sorting callback must handle any value from any array in any order, regardless of the order they were originally provided. This is because each individual array is first sorted before being compared against other arrays. For example: <?php $arrayA = ["string", 1]; $arrayB = [["value" => 1]]; // $item1 and $item2 can be any of "string", 1 or ["value" => 1] $compareFunc = static function ($item1, $item2) { $value1 ...

Return value

Returns an array containing all the values of array that are not present in any of the other arguments.

Example

A runnable snippet:

// Arrays to compare $array1 = array(new stdClass, new stdClass, new stdClass, new stdClass, ); $array2 = array( new stdClass, new stdClass, ); // Set some properties for each object $array1[0]->width = 11; $array1[0]->height = 3; $array1[1]->width = 7; $array1[1]->height = 1; $array1[2]->width = 2; $array1[2]->height = 9; $array1[3]->width = 5; $array1[3]->height = 7; $array2[0]->width = 7; $array2[0]->height = 5; $array2[1]->width = 9; $array2[1]->height = 2; function compare_by_area($a, $b) { $areaA = $a->width * $a->height; $areaB = $b->width * $b->height; if ($areaA < $areaB) { return -1; } elseif ($areaA > $areaB) { return 1; } else { return 0; } } print_r(array_udiff($array1, $array2, 'compare_by_area'));

Output:

Array ( [0] => stdClass Object ( [width] => 11 [height] => 3 ) [1] => stdClass Object ( [width] => 7 [height] => 1 ) )

See also

array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc(), array_uintersect_uassoc()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_udiff() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.