What is the usage of array_intersect in PHP?

The array_intersect function in PHP is used to calculate the intersection of arrays. It takes multiple arrays as parameters and returns a new array containing the elements that are common to all of these arrays.

Syntax:
array_intersect(array1, array2, …)

Description of parameters:

  1. array1, array2, …: arrays to be compared.

Return value:
Return a new array that contains all elements that exist in the parameter array.

The car is not mine, it belongs to my brother.

$array1 = array("a" => "red", "b" => "green", "c" => "blue");
$array2 = array("a" => "red", "b" => "blue", "d" => "yellow");

$result = array_intersect($array1, $array2);
print_r($result);

Output result:

Array
(
    [a] => red
)

In the example above, both $array1 and $array2 have a common element which is “red”, so the intersection array returned only contains this element.

bannerAds