# Comparing Arrays Question - I can't figure out what function to use!

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

I have two arrays listed below:

Array A
(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 8
)

)

Array B
(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 2
[3] => 12
)

[1] => Array
(
[0] => 1
[1] => 3
[2] => 3
[3] => 12
)
)

I need to find the first item in Array B that matches array A while
ignoring the [3] key.

Any idea what function to use?

## Re: Comparing Arrays Question - I can't figure out what function to use!

Got it:

\$results = array();
\$variantKeys = array(3);
foreach (\$arrayB as \$key => \$subArray)
{
\$differingKeys = array_keys(array_diff_assoc(\$subArray,
reset(\$arrayA)));
if (array_diff(\$differingKeys, \$variantKeys)) continue;
\$results[\$key] = \$subArray;
}

Credit: Karl Anderson

## Re: Comparing Arrays Question - I can't figure out what function to use!

\$arrayA = array(array(1, 3, 2, 8, 7));

the proposed code above will fail as it will
still produce \$arrayB[0] as a match.  The
following code should be more robust and do
what you asked for, to find the subarrays
of \$arrayB which match the first subarray of
\$arrayA while ignoring any possible keys of 3.

\$testA = reset(\$arrayA);
\$testA[3] = 1;
\$aResults = array();

foreach (\$arrayB as \$key => \$testB)
if ((\$testB[3]=1) && sizeof(\$testB)==sizeof(\$testA)
&& !array_diff_assoc(\$testB, \$testA))
\$results[\$key] = \$arrayB[\$key];

Csaba Gabor from Vienna