21

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.

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
Nevin Thomas
  • 806
  • 4
  • 12
  • 24

4 Answers4

37

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

$result = array_intersect($array1, $array2);
Expedito
  • 7,771
  • 5
  • 30
  • 43
  • 1
    is there I can loop through the values of $result? I understand that the $result variable will give me an array of key value pairs...but now I only want the values, not the keys. – Sidney Sousa Nov 14 '18 at 15:29
3

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 )

JunM
  • 7,040
  • 7
  • 37
  • 58
  • 2
    can you suggest a reason why your answer is better choice over array_intersect... – Sir Jul 15 '13 at 07:39
1

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

srakl
  • 2,565
  • 2
  • 21
  • 32
0

I think you don't need to use $key=>$value to your problem so check this answer:

<?php
$array1 = array("5", "26", "38", "42");
$array2 = array("15", "36", "38", "42");

foreach ($array1 as $value) {
    if (in_array($value, $array2)) {
        $array3[] = $value;
    }
}

print_r($array3);
?>
Wolph
  • 78,177
  • 11
  • 137
  • 148
gayan
  • 212
  • 1
  • 3