PHP array_intersect Function Explained

This article provides a clear and concise overview of the array_intersect() function in PHP. You will learn about its core purpose, how its syntax works, and how to implement it in your code through practical examples. By the end of this guide, you will understand how to efficiently find matching values across multiple PHP arrays.

Purpose of array_intersect()

The primary purpose of the array_intersect() function is to compare the values of two or more arrays and return the matches. Specifically, it returns a new array containing all the values from the first array that are also present in all the subsequent arrays passed as arguments.

Syntax

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

Key Characteristics

Practical Example

Here is a simple example demonstrating how array_intersect() works with three different arrays:

<?php
$array1 = ["a" => "apple", "b" => "banana", "c" => "cherry"];
$array2 = ["d" => "banana", "e" => "orange", "f" => "apple"];
$array3 = ["apple", "grape", "banana"];

$result = array_intersect($array1, $array2, $array3);

print_r($result);
?>

Output:

Array
(
    [a] => apple
    [b] => banana
)

In this example, “apple” and “banana” are returned because they exist in all three arrays. Note that the keys 'a' and 'b' from the first array are preserved in the final output.

If you need to customize how the arrays are compared, PHP offers several variations of this function: