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 multiple code examples demonstrating how it extracts common elements from two or more arrays.

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

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

Syntax

array_intersect(array1, array2, array3...)

Parameters

array1

: Required, the base array for comparison. 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 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 each example, array_intersect() returns the elements that are common to all provided arrays, demonstrating its usefulness for extracting shared values.

Summary

The array_intersect() function is a commonly used PHP function that conveniently compares and extracts common elements from multiple arrays, helping developers handle array-related logic more efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplesarray_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.