W3docs

PHP Array Intersect_Assoc Function

The array_intersect_assoc function in PHP is an essential tool for comparing two or more arrays and retrieving only the elements that exist in all of them. This

The array_intersect_assoc function in PHP is an essential tool for comparing two or more arrays and retrieving only the elements that exist in all of them. This function can be particularly useful when dealing with associative arrays, as it compares both keys and values of the arrays being compared.

How it Works

The array_intersect_assoc(array $array1, array $array2, array ...$arrays): array function takes two or more arrays as arguments and returns an array containing only the elements that exist in all of the arrays being compared. The elements are compared on both the key and value level, making it particularly useful for associative arrays.

The function works by looping through each element in the first array and comparing it to the corresponding elements in the other arrays. If a match is found on both key and value, the element is added to the final output array. If no match is found, the element is discarded. Note that the comparison is strict: keys and values must be identical (e.g., 1 and '1' are considered different).

Example

Here is a simple example of how the array_intersect_assoc function can be used:

PHP Example of array_intersect_assoc function usage

<?php

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "c" => "red");
$result = array_intersect_assoc($array1, $array2);
print_r($result);

?>

The output of this code would be:


Array
(
    [a] => green
)

As you can see, only the elements that exist in both arrays with identical keys and values are included in the final output. The red element is excluded because its key in $array1 is 0, while in $array2 it is c, demonstrating the function's strict key-value comparison.

Diagram

Here is a visual representation of how the array_intersect_assoc function works:


graph LR
A[Array 1: key-value pairs] -->|Compare keys & values| B[Array 2: key-value pairs]
B -->|Keep only matching pairs| C[Result Array]

Conclusion

The array_intersect_assoc function in PHP is a powerful tool for comparing arrays and retrieving only the elements that exist in all of them. Whether you're dealing with associative arrays or simple arrays, this function can help simplify your code and streamline your workflow.

Practice

Practice

What does the array_intersect_assoc() function in PHP do?