PHP Array array_intersect() Function (With Examples)

In this tutorial, we will learn about the PHP array_intersect() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_intersect() Function

The array_intersect() function is used to find the matched elements from two or more elements. Function “array_intersect()” compares the values of the first array with the other arrays and returns matched elements.

Syntax

The syntax of the array_intersect() function:

array_intersect(array1, array2, [array3,...]);

Parameters

The parameters of the array_intersect() function:

  • array1, array2 are the input arrays other arrays are an optional.

Return Value

The return type of this method is array, it returns an array containing all of the values in array whose values exist in all of the parameters. [Source]

Sample Input/Output

Input:
$arr1 = array("Hello", "Hi", "Okay", "Bye!");
$arr2 = array("Okay", "Hello", "Bye", "Hi");

Function calling: 
array_intersect($arr1, $arr2);

Output:
Array
(
    [0] => Hello
    [1] => Hi
    [2] => Okay
)

PHP array_intersect() Function Example 1

Comparing two string arrays.

<?php
//input array1    
$arr1 = array("Hello", "Hi", "Okay", "Bye!");
//input array2
$arr2 = array("Okay", "Hello", "Bye", "Hi");

//finding matched elements
$ans = array_intersect($arr1, $arr2);

print_r ($ans);
?>

Output

The output of the above example is:

Array
(
    [0] => Hello
    [1] => Hi
    [2] => Okay
)

PHP array_intersect() Function Example 2

Comparing three arrays with strings & numbers.

<?php
//input array1    
$arr1 = array(10, 20, 30, "Hello", 40, "Hi", 50);
//input array2
$arr2 = array(50, 60, "Hello", 70, 80);
//input array3
$arr3 = array(10, 20, "Hello", 50, "Hi", 30);

//finding matched elements
$ans = array_intersect($arr1, $arr2, $arr3);

print_r ($ans);
?>

Output

The output of the above example is:

Array
(
    [3] => Hello
    [6] => 50
)

To understand the above examples, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.