Example
Compare the key names and key values of the two arrays (use built-in functions to compare key names, use user custom functions to compare key values), and return the difference set:
<?php function myfunction($a,$b) { if ($a===$b) { return 0; } return ($a>$b)?1:-1; } $a1=array("a"=>"red","b"=>"green","c"=>"blue"); $a2=array("a"=>"red","b"=>"blue","c"=>"green"); $result=array_udiff_assoc($a1,$a2,"myfunction"); print_r($result); ?>
Definition and usage
array_udiff() function is used to compare the key names and key values of two (or more) arrays and return the difference.
Note: This function uses built-in functions to compare key names and user-defined functions to compare key values!
This function compares the key names and key values of two (or more) arrays, and returns a difference array, which includes everything in the compared array (array1), but not in any other The key name and key value in the parameter array (array2 or array3, etc.).
Syntax
array_udiff_assoc(array1,array2,array3...,myfunction)
Parameters | Description |
array1 | Required. The first array to compare with other arrays. |
array2 | Required. The array to compare to the first array. |
array3,... | Optional. Additional array to compare with the first array. |
myfunction | Required. A string that defines a callable comparison function. If the first argument is <, =, > and the second argument is, the corresponding comparison function must return an integer of <, =, > 0. |
Technical details
Return value: | Returns a difference array, which includes Returns all key names and values that are in the compared array (array1) but not in any other parameter array (array2 or array3, etc.). |
PHP version: | 5+ |
callback function provided by the user. In this respect, the behavior of array_diff_assoc() is exactly the opposite, which uses the internal function for comparison.
Example<?php class cr { private $priv_member; function cr($val) { $this->priv_member = $val; } static function comp_func_cr($a, $b) { if ($a->priv_member === $b->priv_member) return 0; return ($a->priv_member > $b->priv_member) ? 1 : -1; } } $a = array( "0.1" => new cr(9) , "0.5" => new cr(12) , 0 => new cr(23) , 1 => new cr(4) , 2 => new cr(-15) , ); $b = array( "0.2" => new cr(9) , "0.5" => new cr(22) , 0 => new cr(3) , 1 => new cr(4) , 2 => new cr(-15) , ); $result = array_udiff_assoc($a, $b, array( "cr", "comp_func_cr" )); print_r($result); ?>
Array ( [0.1] => cr Object ( [priv_member:private] => 9 ) [0.5] => cr Object ( [priv_member:private] => 12 ) [0] => cr Object ( [priv_member:private] => 23 ) )
The above is the detailed content of PHP function array_udiff_assoc() is used to compare the key names and key values of two arrays and return the difference set. For more information, please follow other related articles on the PHP Chinese website!