Master PHP’s array_intersect(): Syntax, Parameters, and Real-World Examples

This guide explains PHP’s array_intersect() function, covering its syntax, required and optional parameters, return value, and detailed code examples that demonstrate how to extract common elements from two or more arrays.

php Courses
php Courses
php Courses
Master PHP’s array_intersect(): Syntax, Parameters, and Real-World Examples

Overview

The array_intersect() function in PHP compares the values of two or more arrays and returns a new array containing only the values that exist in all input arrays.

Syntax

array_intersect(array1, array2, array3...)

Parameters

array1 : Required. The base array for comparison.

array2 : Required. The array to compare against array1.

array3, ... : Optional. Additional arrays to compare with array1.

Return Value

The function returns an array containing all values that are present in every input array.

Examples

Example 1

$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 2

$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 3

$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 of Results

In Example 1, $array1 contains "apple", "banana", "orange", and "grape" while $array2 contains "banana", "mango", and "grape". The intersected result includes only the values present in both arrays: "banana" and "grape".

In Example 2, the numeric arrays share the values 4 and 5, which are returned by the function.

In Example 3, three arrays of color strings are compared; only "green" and "blue" appear in all three arrays, so they are returned.

Conclusion

The array_intersect() function is a widely used PHP utility for comparing and extracting common elements across multiple arrays, helping developers handle array‑related logic more efficiently.

backend developmentPHPcode examplesFunctionsarray comparisonarray_intersect
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.