PHP Function Reference

PHP array_uintersect() Function



The PHP array_uintersect() function compares values of an array against one or more other arrays and returns all elements of the first array that are present in all the arguments. This function compares values using a user-defined comparison function.

Unlike array_intersect(), this function uses a user-defined function to compare values.

Syntax

array_uintersect(array, arrays, myfunction)

Parameters

array Required. Specify an array to compare from.
arrays Required. Specify one or more arrays to compare against.
myfunction Required. Specify user-defined function to compare values. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.

Return Value

Returns an array containing all the entries from array whose values exist in all of the arguments.

Exceptions

NA.

Example:

The example below shows the usage of array_uintersect() function.

<?php
function MyFunc($x, $y) {
  if ($x == $y) 
    return 0;
  return ($x < $y)? -1: 1;
}

$Arr1 = array(10, 20, 30, 40, "Hello", "World");
$Arr2 = array(10, 20, 30, "Hello");
$Arr3 = array(30, "Hello", "John");

//comparing Arr1 against Arr2
$Arr1_intersect_Arr2 = 
    array_uintersect($Arr1, $Arr2, 'MyFunc');
print_r($Arr1_intersect_Arr2);

echo "\n";

//comparing Arr1 against Arr2 and Arr3
$Arr1_intersect_All = 
    array_uintersect($Arr1, $Arr2, $Arr3, 'MyFunc');
print_r($Arr1_intersect_All);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [4] => Hello
)

Array
(
    [2] => 30
    [4] => Hello
)

Example:

Consider the example below where array_uintersect() function is used with associative arrays. Please note that, multiple occurrences in Arr1 are all treated the same way.

<?php
function MyFunc($x, $y) {
  if ($x == $y) 
    return 0;
  return ($x < $y)? -1: 1;
}

$Arr1 = array("a"=>"Red",
              "b"=>"Red",
              "c"=>"Blue",
              "d"=>"Blue",
              "e"=>"Green");
$Arr2 = array("p"=>"Red", 
              "q"=>"Black", 
              "r"=>"White",
              "s"=>"Green");

//comparing Arr1 against Arr2
$Arr1_intersect_Arr2 = 
    array_uintersect($Arr1, $Arr2, 'MyFunc');

//displaying the result
print_r($Arr1_intersect_Arr2);

The output of the above code will be:

Array
(
    [a] => Red
    [b] => Red
    [e] => Green
)

❮ PHP Array Reference