PHP array_uintersect() Function
PHP array_uintersect() Function
The array_uintersect() function in PHP calculates the intersection of arrays by comparing the data by a callback function. It returns an array containing all the values of the first input array that are present in all the arguments.
Syntax
array_uintersect ( array $array1 , array $array2 [, array $... ], callable $value_compare_func )
Parameter
array1(required)- This array represents the first input array.
array2(required)- This array represents the second input array.
array3….(optional)- It represents more arrays to compare against.
value_compare_func(required)- This parameter represents a string that describe a callable comparison function. The comparison function returns an integer greater(<), equal to(=), or less than( >) than 0 if the first argument is greater(<), equal to(=), or less than( >) than the second argument.
Return
This function returns an array containing all the values of the first input array that are present in all the given arrays.
Example 1
<?php //initializing the input array1 $array1 = array("1" => "green", "2" => "brown", "3" => "blue", "red"); //initializing the input array2 $array2 = array("1" => "GREEN", "2" => "brown", "yellow", "red"); echo("The array_uintersect() returns:\n "); //returns an array containing all the values of array that exists in all the other given arrays print_r(array_uintersect($array1, $array2, "strcasecmp")); ?>
Output
The array_uintersect() returns: Array ( [1] => green [2] => brown [4] => red )
Example 2
<?php //initializing the input array1 $array1 = array("a" => "mango", "b" => "Grapes", "c" => "Guava", "orange"); //initializing the input array2 $array2 = array("a" => "Mango", "b" => "GRAPES", "yellow", "orange"); echo("The array_uintersect_assoc() returns:\n "); //returns an array containing all the values of array that exists in all the other given arrays $intersection=array_uintersect($array1, $array2, "strcasecmp");//case-insensitive //will return mango, Grapes and orange print_r($intersection); ?>
Output
Array ( [a] => mango [b] => Grapes [0] => orange )
Example 3
<?php //initializing the callable function function compare_function($a, $b) { if ($a===$b) { return 1; } return ($a>$b)? 1: 0; } // initializing the Input Array 1 $array1 = array(05=>"Reema", 10=>"raj", 30=>"Atul"); // initializing the Input Array 2 $array2 = array(20=>"Mahesh", 40=>"Smitha", 30=>"Atul"); // Computes the intersection of arrays $intersection=array_uintersect($array1, $array2, "compare_function"); print_r($intersection); ?>
Output
Array ( [5] => Reema [10] => raj [30] => Atul )