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- $array1: The master array to check outputs against. The keys from this array are preserved in the returned result.
- $array2: The second array to compare values against.
- …$arrays: Optional additional arrays to compare.
Key Characteristics
- Value-Based Comparison: The function only compares the values of the arrays, ignoring the keys.
- Key Preservation: The keys from the first array
(
$array1) are kept for the matching elements in the returned array. - Strict Type Comparison: Elements are compared as
strings. This means that an integer
1and a string'1'are considered equal during the intersection check.
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.
Related Functions
If you need to customize how the arrays are compared, PHP offers several variations of this function:
array_intersect_assoc(): Compares arrays using both values and keys.array_intersect_key(): Compares arrays using only the keys.array_uintersect(): Compares arrays using a user-defined callback function for data comparison.