php intersect array 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: 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