Home » PHP

PHP array_intersect() Function with Example

PHP array_intersect() Function: Here, we are going to learn about the array_intersect() function with example.
Submitted by IncludeHelp, on February 10, 2019

PHP array_intersect() Function

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:

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

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

Examples:

    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 code 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

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

PHP code 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

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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.