Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get common values from two different arrays in PHP [closed]

Tags:

arrays

php

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.

like image 998
Nevin Thomas Avatar asked Jul 15 '13 07:07

Nevin Thomas


People also ask

How do I check if two arrays have the same element in PHP?

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.

Which PHP function returns an array with the elements of two or more arrays in one array?

PHP | Merging two or more arrays using array_merge()

What is array intersect?

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.


2 Answers

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

$result = array_intersect($array1, $array2);
like image 78
Expedito Avatar answered Oct 23 '22 11:10

Expedito


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 )

like image 39
JunM Avatar answered Oct 23 '22 10:10

JunM