How to get common values from two different arrays in PHP

Use this one, though this maybe a long method:

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

$final_array = array();

foreach($array1 as $key=>$val){
    if(in_array($val,$array2)){
        $final_array[] = $val;
    }
}

print_r($final_array);

Result: Array ( [0] => 38 [1] => 42 )


array_intersect() works just fine.

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

echo array_intersect($array1, $array2);

http://fr2.php.net/array_intersect


Native PHP functions are faster than trying to build your own algorithm.

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

Tags:

Php

Arrays