194 of 410 menu

The array_udiff_assoc Function

The array_udiff_assoc function returns an array containing all the values from the first array that are not present in any of the other arrays. Key comparison is performed by PHP's internal mechanism, while value comparison is done using a user-defined callback function.

Syntax

array_udiff_assoc(array $array1, array $array2, ..., callable $value_compare_func): array

Example

Comparing arrays with a custom function:

<?php function compare($a, $b) { return $a <=> $b; } $array1 = ["a" => "green", "b" => "brown", "c" => "blue"]; $array2 = ["a" => "green", "b" => "yellow", "d" => "blue"]; print_r(array_udiff_assoc($array1, $array2, "compare")); ?>

Code execution result:

Array ( [b] => brown [c] => blue )

Example

Comparison with numeric indexes:

<?php function numCompare($a, $b) { return $a - $b; } $array1 = [10 => "apple", 20 => "banana", 30 => "cherry"]; $array2 = [10 => "pear", 20 => "banana", 40 => "cherry"]; print_r(array_udiff_assoc($array1, $array2, "strcmp")); ?>

Code execution result:

Array ( [10] => apple [30] => cherry )

Example

Complex object comparison:

<?php class Product { public $id; public $name; public function __construct($id, $name) { $this->id = $id; $this->name = $name; } } function objCompare($a, $b) { return strcmp($a->name, $b->name); } $products1 = [ "p1" => new Product(1, "Laptop"), "p2" => new Product(2, "Phone") ]; $products2 = [ "p1" => new Product(3, "Tablet"), "p3" => new Product(2, "Phone") ]; print_r(array_udiff_assoc($products1, $products2, "objCompare")); ?>

Code execution result:

Array ( [p1] => Product Object ( [id] => 1 [name] => Laptop ) )

See Also

  • the array_diff_assoc function,
    which computes the difference of arrays with index check
  • the array_udiff function,
    which computes the difference of arrays using a callback function (without index check)
byenru