array intersect php code example

Example 1: php get intersection of two arrays

$array1 = [1, 2];
$array2 = [2, 3, 4];
$commonValue = array_intersect($array1, $array2);
//$commonValue = 2
// If you have X number of arrays you can do:
$array1 = [1, 2];
$array2 = [2, 3, 4];
$arrayOfArrays = [$array1, $array2];
$commonValue = array_intersect(...$arrayOfArrays);

Example 2: array_intersect php

<?php
$a1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$a2 = array("e"=>"red", "f"=>"green", "g"=>"blue");

$result = array_intersect($a1, $a2);
print_r($result); //Array ( [a] => red [b] => green [c] => blue )

Example 3: php array_intersect

<?php
    $array1 = array("a" => "verde", "vermelho", "azul");
    $array2 = array("b" => "verde", "amarelo", "vermelho");
    $result = array_intersect($array1, $array2);
    print_r($result); // Array ( [a] => verde [0] => vermelho ) 
?>

Tags:

Php Example