1

Possible Duplicate:
Find common values in multiple arrays with PHP

I have two arrays with the same indexes like ,

$a=Array
(
    [2013-01-15] => Array
        (
            [0] =>1001 
            [1] => 1002
            [2] => 1003
            [3] => 1004
            [4] => 1005
            [5] => 1006
            [6] => 1007
)
and 
$b=Array
(
    [2013-01-15] => Array
        (
            [0] =>1001 
            [1] => 
            [2] => 1003
            [3] => 
            [4] => 
            [5] => 1007
            [6] => 
)

Now I would like to compare this data and to find out how many number of same elements are there. In this case there are three elements in common.

Community
  • 1
  • 1
Happy Coder
  • 4,255
  • 13
  • 75
  • 152

2 Answers2

4

Use array_intersect

$result = array_intersect($a['2013-01-15'], $b['2013-01-15']);

Example from manual:

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);  

Array
(
    [a] => green
    [0] => red
)
Ben
  • 51,770
  • 36
  • 127
  • 149
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
1

Do you know the PHP array_intersect function? It might be what you are looking for...

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

array_intersect() retourne un tableau contenant toutes les valeurs de array1 qui sont présentes dans tous les autres arguments array2, ..., etc. Notez que les clés sont préservées.

You will need a flat array though. You can have a look at that question on how to do that: How to Flatten a Multidimensional Array?

In your case, provided your arrays are always made of array values and you need to count the duplicates within those:

$a = array( '2012-04' => array( 10, 50, 60, 80 ) );
$b = array( '2012-04' => array( 10, 40, 80 ) );

$count = 0;
foreach ( $a as $key => $array1 ) {
  if ( array_key_exists( $key, $b ) ) {
    $array2 = $b[ $key ];
    $count += count( array_intersect( $array1, $array2 ) );
  }
}
Community
  • 1
  • 1
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124