PHP array intersect

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP : array_intersect() function

PHP: Computes the intersection of arrays

The array_intersect() function is used to compare two or more arrays and returns an array containing all the values of the first array that are present in other arrays. In this operation, keys are preserved.

Version

(PHP 4 and above)

Syntax

array_diff (array1, array2, array3 ... )

Parameters

Name

Description

Required /
Optional

Type

array1

Reference array.

Required

Array

array2

Compared with the first array.

Required

Array

array3..

Compared with the first array

Optional

Array

Return value

An array containing all the keys and values in array1 if it's values exist in array2, array3 etc.

Value Type : Array

Pictorial Presentation

php array array_intersect() function

Example :

  1. $array1=array("Orange" => 100, "Apple" => 200, "Banana" => 300, "Cherry" => 400);  

  2. $array2=array("Orange" => 100, "Apple" => 200, "Banana" => 300);  

  3. $result=array_intersect($array1, $array2);  

  4. print_r($result);  

  5. ?>  

Output :

Array ( [Orange] => 100 [Apple] => 200 [Banana] => 300 )