# Compare each distinct pair of the entires in the 1D associative arrays

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

•  Subject
• Author
• Posted on
Dear All:

For the indexed 1D array, I can easily use the following statements:

for (\$index2 = 0; \$index2 < \$size; \$index2++){
for (\$index1 = \$index2+1; \$index1 < \$size; \$index1++)

to compare each distinct pair of the entires in the 1D array (the
upper triangle of the n*n square).

For the associative arrays, how can I do that?

Thanks.

Du

## Re: Compare each distinct pair of the entires in the 1D associative arrays

On Feb 16, 7:30 pm, Jer...@thebunnyshed.co.uk wrote:

I know foreach.  But using foreach how to do it?

## Re: Compare each distinct pair of the entires in the 1D associative arrays

You can get random access to keys using the array returned by
array_keys().

If it's the case that the arrays don't have the same keys or you can
have duplicate keys in an array (unlike your numerical array example),
then you can keep track of pairs that have already been seen, e.g.:

if (isset(\$seen[\$k][\$j])) continue;

\$seen[\$j][\$k] = true;
\$seen[\$k][\$j] = true;

wrote:

## Re: Compare each distinct pair of the entires in the 1D associative arrays

Thanks.  But if considering the efficiency of the PHP program, I think
foreach would be much faster.  Right?

## Re: Compare each distinct pair of the entires in the 1D associative arrays

Dear petersprc:

If we use array_keys() to extract all keys, we just use the
traditional indexed array of keys to keep track of all pair of keys
from this 1D array, why bothering us to declare a new 2D array,
\$seen[\$j][\$k]?

## Re: Compare each distinct pair of the entires in the 1D associative arrays

Yeah, in the second case array_keys isn't applicable

\$seen is needed if you're checking unique key pairs and there are no
restrictions on the array contents.

## Re: Compare each distinct pair of the entires in the 1D associative arrays

duzhidian@gmail.com wrote:

Du,

Something like:

\$match = true;
if (count(\$array1) != count(\$array2)) {
\$match = false;
else {
foreach (\$array1 as \$key->\$value) {
if (!isset(\$array2[\$key]) || \$array2[\$key] <> \$value) {
\$match = false;
break;
}
}
}

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================