4

I would like to know how to compare two two-dimension arrays value.

First array

Array 1
(
    [0] => Array
        (
            [0] => a
        )

    [1] => Array
        (
            [0] => b
        )

    [2] => Array
        (
            [0] => c
        )

}

Second one

Array 2
(
    [0] => Array
        (
            [0] => a
        )

    [1] => Array
        (
            [0] => d
        )

    [2] => Array
        (
            [0] => e
        )

}

I need to make my loop to compare the arrays and check the matched value. In my case, array1[0][0]=a matches array2[0][0]=a. If it matches, php will output some html.

My foreach loop

foreach ($array1 as $arrays){
    foreach($arrays as $array){
      //need to compare array2 here not sure how to do it.
    }
}
2
  • "I need to know if my loop could compare the arrays to check the matched value." – well, save your file and give it a try ;) Commented May 30, 2010 at 2:44
  • ....I don't have anything to try...:( Commented May 30, 2010 at 2:46

2 Answers 2

2
foreach($array1 as $k1 => $arrays) {
    foreach($arrays as $k2 => $val) {

        if($array2[$k1][$k2] == $val) {
            // $array1[$k1][$k2] is equal to $array2[$k1][$k2]
        }
    }
} // end of foreach

The foreach($a as $k => $v) syntax does the same thing as foreach($a as $v), except that it also puts the key associated with the value into $k.

Sign up to request clarification or add additional context in comments.

1 Comment

@mattbasta: No, it shouldn't.
1

You can use array_diff_assoclike so

if(count(array_diff_assoc($array1,array2) != 0))
{
   //Arrays are not the same
}else{
  echo 'these following items are differing in throughout the arrays . ' . print_r(array_diff_assoc($array1,array2),true);
}

Hope this helps you.

Also take note of array_diff_assoc, it returns the array items that are found to be different to the other array including its index keys.

2 Comments

It should be noted that this function is SLOOOOOWWWWWWW. Great if you've got small arrays, but it gets exponentially slower as you add lots of elements to them.
Amber got what I need. Thanks for the tip though. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.