Using array_intersect_uassoc() to Compute Array Intersection with Key Comparison in PHP

This article explains the PHP function array_intersect_uassoc, which returns the intersection of arrays while comparing both keys and values, describes its parameters and return value, and provides a complete example with a custom key comparison callback and the resulting output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_intersect_uassoc() to Compute Array Intersection with Key Comparison in PHP

The array_intersect_uassoc() function in PHP returns an array containing all values from the first array that are present in all other arrays, using both key names and values for comparison.

Function signature:

array_intersect_uassoc(array $array1, array $array2, callable $key_compare_func)

Parameters:

array1 : The first array to compare.

array2 : One or more arrays to compare against the first array.

key_compare_func : A callable that compares keys; it must return an integer less than, equal to, or greater than zero when the first key is respectively less than, equal to, or greater than the second.

Return value: An array containing the intersection of the arrays, where both keys and values match across the compared arrays.

Example usage:

<?php
$array1 = array(
    "a" => "green",
    "b" => "brown",
    "c" => "blue",
    "d" => "red"
);

$array2 = array(
    "a" => "GREEN",
    "b" => "brown",
    "e" => "yellow",
    "f" => "red"
);

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

Output:

Array
(
    [b] => brown
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPphp-arrayarray_intersect_uassockey comparisonarray-functions
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.