Backend Development 4 min read

PHP array_intersect() Function: Syntax, Parameters, Return Value, and Practical Examples

This article explains PHP's array_intersect() function, covering its syntax, required and optional parameters, return value, and provides three detailed code examples that demonstrate how to extract common elements from multiple arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP array_intersect() Function: Syntax, Parameters, Return Value, and Practical Examples

In PHP, the array_intersect() function compares 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. An 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

In Example 1, $array1 contains "apple", "banana", "orange", and "grape" while $array2 contains "banana", "mango", and "grape". The intersected result includes the common values "banana" and "grape".

In Example 2, $array1 holds numbers 1‑5 and $array2 holds 4‑7. The function returns the shared numbers 4 and 5.

In Example 3, three arrays of color strings are compared; the common colors across all three arrays are "green" and "blue".

Summary

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

Backend Developmentphpcode examplesarray-functionsarray_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

login 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.