← Back to Chapters

PHP Array Intersect Functions

? PHP Array Intersect Functions

? Quick Overview

PHP array intersect functions help identify common elements between arrays. They are commonly used when comparing datasets, filtering values, or matching keys across arrays.

⚡ Key Concepts

  • array_intersect() compares array values
  • array_intersect_key() compares array keys
  • Original keys are preserved in results

? Syntax / Theory

array_intersect() returns values present in all arrays, while array_intersect_key() returns key-value pairs with matching keys.

? Example 1: array_intersect()

? View Code Example
// Find common values between two arrays
<?php
$array1 = array("a" => "apple", "b" => "banana", "c" => "cherry");
$array2 = array("d" => "date", "b" => "banana", "e" => "elderberry");
$common = array_intersect($array1, $array2);
print_r($common);
?>

? Output Explanation

The value banana exists in both arrays, so it is returned with its original key.

? Example 2: array_intersect_key()

? View Code Example
// Find matching keys between two arrays
<?php
$array1 = array("a" => "apple", "b" => "banana", "c" => "cherry");
$array2 = array("b" => "blueberry", "c" => "citrus", "d" => "date");
$result = array_intersect_key($array1, $array2);
print_r($result);
?>

? Output Explanation

Keys b and c exist in both arrays, so their values from the first array are returned.

? Example 3: Multiple Arrays

? View Code Example
// Compare multiple arrays to find common values
<?php
$a1 = array("apple", "banana", "cherry");
$a2 = array("banana", "cherry", "date");
$a3 = array("cherry", "date", "elderberry");
$result = array_intersect($a1, $a2, $a3);
print_r($result);
?>

? Use Cases

  • Finding common users between lists
  • Filtering shared permissions
  • Comparing product inventories

✅ Tips & Best Practices

  • Use array_values() if reindexing is required
  • Ensure consistent data types for accurate comparison
  • Choose value-based or key-based comparison carefully

? Try It Yourself

  • Create numeric arrays and find common elements
  • Compare associative array keys
  • Test with mixed data types