How to get common values from two different arrays in PHP [closed]
I have two arrays with some user-id
$array1 = array("5","26","38","42");
$array2 = array("15","36","38","42");
What I need is, I need the common values from the array as follows
$array3 = array(0=>"38", 1=>"42");
I have tried array_intersect()
. I would like to get a method that takes a minimum time of execution. Please help me, friends.
Native PHP functions are faster than trying to build your own algorithm.
$result = array_intersect($array1, $array2);
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 )