PHP Tutorial - PHP array_intersect() Function


The array_intersect() function returns a new array containing all the values of array $arr1 that exist in array $arr2.

You can intersect several arrays simultaneously by providing more parameters to the function. For example:

$arr1_shared = array_intersect($arr1, $arr2, $arr3, $arr4);


PHP array_intersect() Function has the following syntax.

array array_intersect ( array arr1, array arr2 [, array ...] )


ParameterIs RequiredDescription
array1Required.Array to compare from
array2Required.Array to compare against
array3,...Optional.Arrays to compare against

Example 1

    $toppings1 = array("A", "B", "C", "");
    $toppings2 = array("C", "", "D");
    $int_toppings = array_intersect($toppings1, $toppings2);

The code above generates the following result.

Example 2

The array_intersect() function will try to retain array keys when possible. For example, if you are intersecting two arrays that have no duplicate keys, all the keys will be retained. However, if there are key clashes, array_intersect() will use the first array to contain it. For example:

    $arr1 = array("A"=>25, "B"=>38, "C"=>27);
    $arr2 = array("B"=>99, "D"=>38);
    var_dump(array_intersect($arr1, $arr2));

The code above generates the following result.