FLY
FLY

Reputation: 2459

comparing nested arrays for equality

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

Upvotes: 0

Views: 92

Answers (3)

Richard
Richard

Reputation: 61409

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.

Upvotes: 1

Pez Cuckow
Pez Cuckow

Reputation: 14422

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())

Upvotes: 0

Jon
Jon

Reputation: 437604

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.

Upvotes: 3

Related Questions