Array Functions
Advertisements

PHP array_uintersect_uassoc() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_uintersect_uassoc() function compares the keys and values of two or more arrays and returns the matches using the user-defined key and value comparison functions.

The following table summarizes the technical details of this function.

Return Value: Returns an array containing all the elements from array1 whose values are present in all of the other arrays.
Version: PHP 5+

Syntax

The basic syntax of the array_uintersect_uassoc() function is given with:

array_uintersect_uassoc(array1, array2, ..., value_compare_function, key_compare_function);

The following example shows the array_uintersect_uassoc() function in action.

<?php
// Define comparison functions
function compareKey($a, $b){
    if($a == $b){
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

function compareValue($a, $b){
    // Converting value to lowercase
    $a = strtolower($a);
    $b = strtolower($b);

    if($a == $b){
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "dog");
$array2 = array("a"=>"APPLE", "B"=>"ball", "c"=>"Cat");

// Computing the intersection
$result = array_uintersect_uassoc($array1, $array2, "compareValue", "compareKey");
print_r($result);
?>

Note: The comparison function must return an integer equal to zero if both arguments are equal, an integer less than zero if the first argument is less than the second, and an integer greater than zero if the first argument is greater than the second argument.


Parameters

The array_uintersect_uassoc() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array to compare from.
array2 Required. Specifies an array to compare against.
... Optional. Specifies more arrays to compare against.
value_compare_function Required. Specifies a callback function to use for value comparison.
key_compare_function Required. Specifies a callback function to use for key comparison.

More Examples

Here're some more examples showing how array_uintersect_uassoc() function actually works:

The following example shows how to compare the keys and values of the three arrays and get the matches using the PHP's built-in strcasecmp() function as comparison function.

<?php
// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");
$array2 = array("A"=>"APPLE", "B"=>"BALL", "C"=>"CAMEL");
$array3 = array("a"=>"Apple", "b"=>"Banana");

// Computing the intersection
$result = array_uintersect_uassoc($array1, $array2, $array3, "strcasecmp", "strcasecmp");
print_r($result);
?>
Advertisements
Bootstrap UI Design Templates