196 of 410 menu

The array_udiff Function

The array_udiff function compares arrays and returns elements from the first array that are not present in the subsequent arrays. For element comparison, it uses a callback function that you define yourself. The first parameter is the main array for comparison, the subsequent parameters are arrays to compare against the first one.

Syntax

array_udiff(array1, array2, ..., callback): array;

Example

Let's compare two arrays of numbers using a callback function for comparison:

<?php $arr1 = [1, 2, 3, 4, 5]; $arr2 = [3, 4, 5, 6, 7]; $res = array_udiff($arr1, $arr2, function($a, $b) { return $a <=> $b; }); print_r($res); ?>

Code execution result:

[1, 2]

Example

Let's compare arrays of strings using a custom comparison function:

<?php $arr1 = ['a', 'b', 'c', 'd']; $arr2 = ['c', 'd', 'e', 'f']; $res = array_udiff($arr1, $arr2, function($a, $b) { return strcmp($a, $b); }); print_r($res); ?>

Code execution result:

['a', 'b']

Example

Comparison with multiple arrays:

<?php $arr1 = [1, 2, 3, 4, 5]; $arr2 = [2, 3, 4]; $arr3 = [3, 4, 5]; $res = array_udiff($arr1, $arr2, $arr3, function($a, $b) { return $a <=> $b; }); print_r($res); ?>

Code execution result:

[1]

See Also

  • the array_diff function,
    which computes the difference of arrays
  • the array_intersect function,
    which computes the intersection of arrays
  • the array_udiff_assoc function,
    which computes the difference with additional index check
byenru