PHP array_intersect_assoc() function

Example

Compare the keys and values of two arrays and return the intersection:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2 = array("a" => "red", "b" => "green", "c" => "blue");
$result=array_intersect_assoc($a1, $a2);
print_r($result);
?>

Run Instance

Definition and Usage

The array_intersect_assoc() function is used to compare the keys and values of two (or more) arrays and returns the intersection.

This function compares the keys and values of two (or more) arrays and returns an intersection array, which includes all elements present in all compared arrays (array1in, as well as in any other parameter arrays (array2 or array3 etc.) of the key names and values.

Description

The array_intersect_assoc() function returns an intersection array of two or more arrays.

vs array_intersect( The difference between this function and array_intersect() is that this function not only compares key values but also compares key names. The key names of the elements in the returned array remain unchanged.

Syntax

array_intersect_assoc(array1,array2,array3...)
Parameters Description
array1 Required. The first array to compare with other arrays.
array2 Required. The array to compare with the first array.
array3,... Optional. Other arrays to compare with the first array.

Technical Details

Return Value: Returns an intersection array that includes all the elements from the arrays being compared (array1in, as well as in any other parameter arrays (array2 or array3 etc.) of the key names and values.
PHP Version: 4.3.0+

More Examples

Example 1

Compare the key names and values of three arrays and return the intersection:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","b"=>"green","g"=>"blue");
$a3=array("a"=>"red","b"=>"green","g"=>"blue");
$result=array_intersect_assoc($a1,$a2,$a3);
print_r($result);
?>

Run Instance