PHP array_udiff() Function

PHP array_udiff() function “compares the different values of two or more arrays using the user-defined function for data comparison and returns the differences“.

Syntax

array_udiff($array1, $array2, $array3, ..., myfunction)

Parameters

  1. The array1 parameter is required. The array to compare from.
  2. The array2 parameter is required, and an array to compare against.
  3. The array3 parameter is Optional and has more arrays to compare against.
  4. The myfunction is required, and a string defines the callable comparison function. The comparison function must return the integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.

Return value

It returns an array of values containing the first array, which is present in all other arrays. If all are the same, then the array returns a NULL array.

Visual RepresentationVisual Representation of PHP array_udiff() Function

Example 1: How to Use PHP array_udiff() function

<?php
 
 function compare($a, $b)
 {
   if ($a===$b)
   {
     return 0;
   }
   return ($a > $b) ? 1 : -1;
 }
 
 $arr1 = array("e" => "Eleven", "m" => "Millie Bobby Brown", "n" => "Noah Schnapp");
 $arr2 = array("el" => "Eleven", "f" => "Finn Wolfhard", "c" => "Caleb Mclaughlin");
 
 $finalArray = array_udiff($arr1, $arr2, "compare");
 print_r($finalArray);

Output

Array ( 
 [m] => Millie Bobby Brown 
 [n] => Noah Schnapp 
)

In this example, array_udiff() uses the user-defined compare function to compare the values between $arr1 and $arr2. It returns an array containing all the values from $arr1 that are not present in $arr2, according to the comparison logic defined in compare.

Example 2: Compare three arraysVisual Representation of Compare three arrays

<?php
 
 function compare($a, $b)
 {
   if ($a===$b)
  {
   return 0;
  }
  return ($a > $b) ? 1 : -1;
 }
 
 $arr1 = array("e" => "Eleven", "m" => "Millie Bobby Brown", "n" => "Noah Schnapp");
 $arr2 = array("el" => "Eleven", "f" => "Finn Wolfhard", "c" => "Caleb Mclaughlin");
 $arr3 = array("d" => "David Harbour", "w" => "Winona Ryder", "j" => "Noah Schnapp");
 
 
 $finalArray = array_udiff($arr1, $arr2, $arr3, "compare");
 print_r($finalArray);

Output

Array
(
  [m] => Millie Bobby Brown
)

Example 3: All elements are same

<?php
 
 function compare($a, $b)
 {
   if ($a===$b)
   {
     return 0;
   }
    return ($a > $b) ? 1 : -1;
 }
 
 $arr1 = array("e" => "Eleven", "m" => "Millie Bobby Brown", "n" => "Noah Schnapp");
 $arr2 = array("e" => "Eleven", "m" => "Millie Bobby Brown", "n" => "Noah Schnapp");

 $finalArray = array_udiff($arr1, $arr2, "compare");
 print_r($finalArray);

Output

Array
(
)

In the above example, Since there are no different values between $arr1 and $arr2 as per function’s logic. So it returns NULL.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.