Skip to content

comparing nested arrays for equality

An answer to this question on Stack Overflow.

Question

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

Answer

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.