Search in a 2D array… php
-
16-10-2019 - |
Question
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.
OTHER TIPS
You could reference to here: http://hk2.php.net/manual/en/function.array-key-exists.php#92355
The above works if all you need is a yes/no (true/false) answer on your search but it doesn't return the found element additional info (from the other array dimension, for instance).
Check out this loop in the PHP manual:
http://php.net/manual/en/control-structures.foreach.php
and combine it with an if
clause to get more
I'm not giving you a direct answer cause foreach
is a part of PHP basics you need to learn.