Understanding array_intersect Function in PHP

The array_intersect() function in PHP is used to find the common elements between two or more arrays. It returns a new array containing only the values that are present in all the provided arrays.

The function compares the values and does not consider the keys.

Here's the syntax of the array_intersect function:

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

 

 
 
$vehicles1 = array("Car", "Bus", "Bicycle", "Motorcycle");
 
$vehicles2 = array("Car", "Bicycle", "Train", "Scooter");
 
$result = array_intersect($vehicles1, $vehicles2);
 
print_r($result);
 
//Output
Array
(
    [0] => Car
    [2] => Bicycle
)
 
 

In this example, the intersection of the two arrays $vehicles1 and $vehicles2 is found, and the result is an array containing common elements "Car" and "Bicycle".

Multidimensional arrays

$students1 = array(
  "John" => array("age" => 20, "course" => "Computer Science"),
  "Mary" => array("age" => 18, "course" => "Literature"),
  "David" => array("age" => 19, "course" => "Mathematics"),
);
 
$students2 = array(
  "Mary" => array("age" => 18, "course" => "Art History"),
  "David" => array("age" => 19, "course" => "Physics"),
  "Sarah" => array("age" => 22, "course" => "Biology"),
);
 
$sharedStudents = array_intersect_key($students1, $students2);
 
echo "Students present in both lists with their details: ";
 
print_r($sharedStudents);
 
//Output:
(
    [Mary] => Array
        (
            [age] => 18
            [course] => Literature
        )

    [David] => Array
        (
            [age] => 19
            [course] => Mathematics
        )

)

This example uses array_intersect_key to compare student names as keys and only returns students present in both lists, preserving their details.

 

 
$products1 = array("Shirt", "Shoes", "Hat", "Phone", "Laptop");
$products2 = array("Laptop", "Phone", "Jeans", "Bag", "Shirt");
$products3 = array("Watch", "Shoes", "Hat", "Laptop", "Book");
 
$commonProducts = array_intersect($products1, $products2, $products3);
 
echo "Products available in all stores: ";
print_r($commonProducts);
 
//Output
Array
(
    [4] => Laptop

)
 
 

This example shows how array_intersect can be used with multiple arrays to find common elements across them, like products available in all three stores.