The array_intersect Function

The array_intersect function computes the intersection of arrays - it returns an array of elements that are present in all arrays passed to the function.

Syntax

phparray_intersect(array $array, array ...$arrays): array

Example

Let's find which elements are present in both arrays:

php<?php
  $arr1 = [1, 2, 3, 4, 5];
  $arr2 = [3, 4, 5, 6, 7];
  
  $res = array_intersect($arr1, $arr2);
  var_dump($res);
?>

Code execution result:

php[3, 4, 5]

Example

Let's find which common elements are present in three arrays:

php<?php
  $arr1 = [1, 2, 3, 4, 5];
  $arr2 = [3, 4, 5, 6, 7];
  $arr3 = [4, 5, 6, 7, 8];
  
  $res = array_intersect($arr1, $arr2, $arr3);
  var_dump($res);
?>

Code execution result:

php[4, 5]

See Also

  • the array_diff function,
    which computes the difference of arrays