PHP array_intersect() - Complete Guide with Examples

Mahesh Mahesh Waghmare
3 min read

The array_intersect() function finds values present in all given arrays. It’s essential for finding common elements, filtering data, and set operations.

This guide covers everything about array_intersect(), from basic usage to advanced patterns.

Introduction to array_intersect()

array_intersect() returns an array containing all values from the first array that are present in all other arrays.

Key Characteristics:

  • Compares values only (not keys)
  • Uses loose comparison (==)
  • Preserves keys from first array
  • Returns new array

Common Use Cases:

  • Find common values
  • Filter arrays
  • Set intersection operations
  • Data comparison
  • Permission checking

Syntax and Parameters

Function Signature

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

Parameters

$array (required): First array to compare ...$arrays (optional): Additional arrays to compare

Return Value

Returns array with values present in all arrays, preserving keys from first array.

Advertisement

Basic Usage Examples

Two Arrays

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];

$intersect = array_intersect($array1, $array2);
// Result: [2 => 3, 3 => 4, 4 => 5]

String Arrays

$array1 = ['apple', 'banana', 'orange'];
$array2 = ['banana', 'grape', 'orange'];

$intersect = array_intersect($array1, $array2);
// Result: [1 => 'banana', 2 => 'orange']

Multiple Array Intersection

$array1 = [1, 2, 3, 4, 5];
$array2 = [2, 3, 4];
$array3 = [3, 4, 5];

$intersect = array_intersect($array1, $array2, $array3);
// Result: [2 => 3, 3 => 4]
// Values present in all three arrays

Key Preservation

Keys from the first array are preserved:

$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = [2, 3];

$intersect = array_intersect($array1, $array2);
// Result: ['b' => 2, 'c' => 3]

Real-World Examples

Find Common Users

$group1 = [1, 2, 3, 4, 5];
$group2 = [3, 4, 5, 6, 7];

$common = array_intersect($group1, $group2);
// Result: Users in both groups

Permission Checking

$required = ['read', 'write', 'delete'];
$userPermissions = ['read', 'write', 'admin'];

$hasAll = count(array_intersect($required, $userPermissions)) === count($required);
// Check if user has all required permissions
Advertisement

Conclusion

array_intersect() finds:

  • Common values across arrays
  • Set intersections for data operations
  • Filtering based on multiple arrays

Key Points:

  • Compares values only
  • Preserves keys from first array
  • Works with multiple arrays
  • Uses loose comparison

Mastering array_intersect() enhances your PHP array manipulation capabilities.

Advertisement
Mahesh Waghmare

Written by Mahesh Waghmare

I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.

Follow on Twitter

Read Next