PHP array_intersect() 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("e" => "red", "f" => "green", "g" => "blue");
$result=array_intersect($a1, $a2);
print_r($result);
?>

Run Instances

Definition and Usage

The array_intersect() 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 that includes all elements present in the compared arrays (array1)}array2 or array3 etc.)

Description

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

The result array includes all values that are present in the compared arrays and also appear in all other parameter arrays, with the key names unchanged.

Note:Only values are used for comparison.

Syntax

array_intersect(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 keys that are present in the compared array (array1) and also in any other parameter arrays (array2 or array3, etc.).
PHP Version: 4.0.1+

More Examples

Example 1

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

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");
$result=array_intersect($a1,$a2,$a3);
print_r($result);
?>

Run Instances