Search code examples
phpmultidimensional-arrayarray-key

Search in a 2D array... php


I have this array:

$Fruit = array()

$Fruit[$species][$property] = $value

Array
(
    [Apple] => Array
        (
            [Green] => 4
            [Spots] => 3
            [Red] => 3
            [Spots] => 2
        )

Now I want to search if a key exists in the second array...

I tried this:

if (!array_key_exists($property, $Fruit->$species))

But it doesn't work...

Does anybody knows how to search inside an array of an array...?

Regards, Thijs


Solution

  • array_key_exists($property, $Fruit[$species])
    

    -> is for objects, [] is for writing to and reading from arrays.

    BTW, unless your values can be null, I'd recommend isset instead of array_key_exists:

    isset($Fruit[$species][$property])
    

    Should be more intuitive.