0

Given the following arrays:

$array[0]['tid'] = 'valueX';
$array[1]['tid'] = 'valueY';

$array2[0]['tid'] = 'valueZ';
$array2[1]['tid'] = 'valueY';

My goal is to check if any of the values in $array are in $array2

Below is what I came up with but I'm wondering if there is a easier / better solution? Maybe something that gets only the values of an array or removes the 'tid' key.

foreach($array as $arr) {
    $arr1[] = $arr['tid'];
}

$flag = 0;

foreach($array2 as $arr) {
    if( in_array( $arr['tid'], $arr1 ) ) {
        $flag++;
    }
}
echo $flag; // number of duplicates
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
FLY
  • 2,379
  • 5
  • 29
  • 40

3 Answers3

3

One way you could approach this:

$extractor = function($row) { return $row['tid']; };
echo "Duplicates: ".count(array_intersect(
    array_map($extractor, $array),
    array_map($extractor, $array2)
));

What this does is pull out the tid value from each array element on both arrays, then intersecting the results (to find values present in both arrays). It might make sense to tweak it a bit or keep the interim results around depending on what exactly you intend to do.

See it in action.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • thanks this is great! exacly what I was looking for! didn't know you could use functions this way +1 – FLY Sep 18 '12 at 11:47
1

You could try using array_map to pull values from the arrays.

The transformed arrays could then be looped with the in_array function. Better, you could use array_intersect which will return the elements common to both transformed arrays.

You may also find that flattening your array can sometimes yield a quick and dirty solution, though PHP does not (to my knowledge) have a built in function for this the linked posted has several variants.

Community
  • 1
  • 1
Richard
  • 56,349
  • 34
  • 180
  • 251
0

If you just want how many are matching the code you have posted will work

You could try using array_map to pull the values

array_map(function($array){return $array['tid']}, $inputArray())

Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130