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.
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.
PHP | Merging two or more arrays using array_merge()
The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With