Backend Development 3 min read

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

This article explains PHP's array_intersect() function, detailing its syntax, required and optional parameters, return value, and provides three practical code examples with outputs to illustrate how it extracts common elements from multiple arrays.

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

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

Syntax

array_intersect(array1, array2, array3...)

Parameters

array1 : Required. The array to compare against.

array2 : Required. The array to compare with array1 .

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

Return Value

Returns an array containing all values that exist 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 each example, array_intersect() returns the values that are common to all provided arrays.

Summary

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

BackendPHParray-functionsarray_intersectphp tutorial
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.