Current Location: Home> Latest Articles> PHP array_intersect() Function Explained with Practical Examples

PHP array_intersect() Function Explained with Practical Examples

M66 2025-07-09

Introduction to array_intersect() Function

In PHP, the array_intersect() function is used to compare the values of two or more arrays and return a new array containing the values that exist in all the input arrays.

Syntax

array_intersect(array1, array2, array3...)

array1: Required. The base array to compare from.
array2: Required. The array to compare against array1.
array3,...: Optional. Additional arrays to compare.

Return Value

Returns an array containing the values that are present in all the input arrays. The keys from array1 are preserved.

Usage Examples

Below are some common usage scenarios for array_intersect():

Example: Intersection of String Arrays

$array1 = array("apple", "banana", "orange", "grape");
$array2 = array("banana", "mango", "grape");
$result = array_intersect($array1, $array2);
print_r($result);

Output:

Array
(
    [1] => banana
    [3] => grape
)

Example: Intersection of Numeric Arrays

$array1 = array(1, 2, 3, 4, 5);
$array2 = array(4, 5, 6, 7);
$result = array_intersect($array1, $array2);
print_r($result);

Output:

Array
(
    [3] => 4
    [4] => 5
)

Example: Intersection of Multiple Arrays

$array1 = array("red", "green", "blue");
$array2 = array("green", "blue", "yellow");
$array3 = array("blue", "yellow", "pink");
$result = array_intersect($array1, $array2, $array3);
print_r($result);

Output:

Array
(
    [1] => green
    [2] => blue
)

Explanation

In practical development, array_intersect() is widely used in data filtering, permission matching, tag comparison, and other scenarios. For instance, when you need to find common elements from multiple sources of data, this function can help you achieve that easily and effectively.

Conclusion

array_intersect() is a highly useful function in PHP that allows you to quickly identify common elements between arrays. By leveraging this function effectively, developers can improve efficiency in array data processing and simplify their code logic.