0

I have Array #1 which contains:

Array
(
    [attribute_pa_color] => blue
    [attribute_pa_size] => large
)

I have Array #2 which contains:

Array
(
    [4624] => Array
        (
            [attribute_pa_color] => blue
            [attribute_pa_size] => large
        )

    [4625] => Array
        (
            [attribute_pa_color] => blue
            [attribute_pa_size] => medium
        )

    [4626] => Array
        (
            [attribute_pa_color] => blue
            [attribute_pa_size] => small
        )

)

How can I find the array key from Array #2 where the inner keys and values match Array 1's?

I have been experimenting with multiple foreach's but I can't seem to get this right, this is my current idea:

$i = 0;
foreach( $array_2 as $array2_key => $array2_array ) {

    foreach( $array2_array as $a2_key => $a2_value ) {

        if( $a2_value == $array1[$a2key] ) {

            $i = $i + 1;

            if( $i == count( $array1 ) ) {

                $break = 1;

            }

            if( $break == 1 ) {

                break;

            }

        }

    }

    if( $break == 1 ) {

        echo 'key is: ' . $array2_key;

        break;

    }

}
bigdaveygeorge
  • 947
  • 2
  • 12
  • 32
  • i hope $array1 assigned properly. what is $in ? why $ break , then break ? is your executing? i think the if condition should work . after that what you want to do? – zod Apr 11 '19 at 19:50
  • $in was a typo, that should have been $i, it is just a counter, I edited the question. The break is done as a condition so I could break both loops. – bigdaveygeorge Apr 11 '19 at 19:54
  • 1
    Just a not that `break;` can be done as `break 2;` to exit both levels of the loops - https://stackoverflow.com/questions/5880442/how-can-i-break-an-outer-loop-with-php – Nigel Ren Apr 11 '19 at 19:57

2 Answers2

3

Arrays can be compared with ==:

foreach ($array2 as $key => $item) {
    if ($item == $array1) {
        echo 'Item with key ' . $key;
    }
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

It's even easier as array_search accepts an array for the needle:

$key = array_search($array1, $array2);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87