0
0
PhpHow-ToBeginner · 3 min read

How to Use array_intersect in PHP: Syntax and Examples

Use array_intersect in PHP to find values that exist in all given arrays. It returns a new array with the common values, preserving keys from the first array.
📐

Syntax

The array_intersect function takes two or more arrays as arguments and returns an array containing all values that are present in every input array. The keys from the first array are preserved in the result.

  • array_intersect(array $array1, array $array2, array ...$arrays): array
  • $array1: The first array to compare.
  • $array2, $arrays: Additional arrays to compare against.
php
array_intersect(array $array1, array $array2, array ...$arrays): array
💻

Example

This example shows how to find common values between three arrays using array_intersect. The result contains only the values that appear in all arrays.

php
<?php
$array1 = ['apple', 'banana', 'cherry', 'date'];
$array2 = ['banana', 'date', 'fig', 'grape'];
$array3 = ['banana', 'date', 'kiwi'];

$result = array_intersect($array1, $array2, $array3);
print_r($result);
?>
Output
Array ( [1] => banana [3] => date )
⚠️

Common Pitfalls

Common mistakes when using array_intersect include:

  • Expecting keys to be reindexed: The function preserves keys from the first array, so keys may be non-sequential.
  • Comparing arrays with different data types: Values are compared with loose equality, so type differences can affect results.
  • Using it with associative arrays expecting key comparison: array_intersect compares values only, not keys.
php
<?php
// Wrong: expecting keys to be reindexed
$array1 = [0 => 'a', 2 => 'b', 5 => 'c'];
$array2 = ['b', 'c', 'd'];
$result = array_intersect($array1, $array2);
print_r($result); // keys 2 and 5 are preserved

// Right: reindex keys if needed
$result_reindexed = array_values($result);
print_r($result_reindexed);
?>
Output
Array ( [2] => b [5] => c ) Array ( [0] => b [1] => c )
📊

Quick Reference

Summary tips for using array_intersect:

  • Returns values common to all arrays.
  • Preserves keys from the first array.
  • Compares values loosely (==).
  • Use array_values() to reindex keys if needed.
  • Only values are compared, not keys.

Key Takeaways

Use array_intersect to get common values from multiple arrays in PHP.
The function preserves keys from the first array, which may not be sequential.
Only values are compared, not keys, and comparison uses loose equality.
Use array_values() to reindex keys if you want a clean numeric index.
array_intersect works best with simple arrays of comparable values.