PHP array_diff_ukey() Function
Topic: PHP Array ReferencePrev|Next
Description
The array_diff_ukey()
function compares the keys of two or more arrays and returns the differences using a user-defined key comparison function.
Also, the values for the keys are not considered in the comparison, only the keys are checked.
The following table summarizes the technical details of this function.
Return Value: | Returns an array containing all the elements from array1 whose keys are not present in any of the other arrays. |
---|---|
Version: | PHP 5.1.0+ |
Syntax
The basic syntax of the array_diff_ukey()
function is given with:
The following example shows the array_diff_ukey()
function in action.
Example
Run this code »<?php
// Define key comparison function
function compare($a, $b){
// Converting key to lowercase
$a = strtolower($a);
$b = strtolower($b);
if($a == $b){
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Sample arrays
$array1 = array("cat"=>2, "lion"=>5, "zebra"=>8);
$array2 = array("CAT"=>3, "FOX"=>1, "LION"=>5, "WOLF"=>7);
// Computing the difference
$result = array_diff_ukey($array1, $array2, "compare");
print_r($result);
?>
Note: The key comparison function must return an integer equal to zero if both keys are equal, an integer less than zero if the first key is less than the second key, and an integer greater than zero if the first key is greater than the second key.
Alternatively, you can simply use the PHP built-in strcasecmp()
function which perform case-insensitive string comparison and returns < 0
if str1 is less than str2; > 0
if str1 is greater than str2, and 0
if they are equal. Therefore, the above example can be rewritten as:
Example
Run this code »<?php
// Sample arrays
$array1 = array("cat"=>2, "lion"=>5, "zebra"=>8);
$array2 = array("CAT"=>3, "FOX"=>1, "LION"=>5, "WOLF"=>7);
// Computing the difference
$result = array_diff_ukey($array1, $array2, "strcasecmp");
print_r($result);
?>
Parameters
The array_diff_ukey()
function accepts the following parameters.
Parameter | Description |
---|---|
array1 | Required. Specifies the array to compare from. |
array2 | Required. Specifies an array to compare keys against. |
... | Optional. Specifies more arrays to compare keys against. |
key_compare_function | Required. Specifies a callback function to use for key comparison. |
More Examples
Here're some more examples showing how array_diff_ukey()
function actually works:
The following example demonstrates how to compare the keys of the three arrays and get the differences using a user-defined key comparison function.
Example
Run this code »<?php
// Sample arrays
$array1 = array("cat"=>2, "lion"=>5, "zebra"=>8);
$array2 = array("BEAR"=>3, "CAT"=>1, "FOX"=>4, "WOLF"=>7);
$array3 = array("elephant"=>1, "tiger"=>2, "zebra"=>5);
// Computing the difference
$result = array_diff_ukey($array1, $array2, $array3, "strcasecmp");
print_r($result);
?>