The in_array function is what you're looking for, this:
in_array([1, 2, 3, 4], 2);
will return true
because 2
exists in the array [1, 2, 3, 4]
. We can use in_array
here to check whether one of the child arrays contain the value you are trying to find.
To do so, we have to iterate over each of the arrays in the initial array.
foreach($results as $result) {
...
}
And then check in_array
against $result
, to check whether $result
contains the value of hob
.
However, once we find the value of hob
, you want the key
returning, this can be done by identifying a key
in the foreach
definition.
foreach($results as $key=>$result) {
echo $key;
} // will output Always on, Laundry, Cooking, ...
So when we iterate over the arrays, once we find the value within an array that we are looking for we are able to return the $key
value.
As a function
function getKeyOfArrayContainingHob($results) {
foreach($results as $key=>$result)
{
if(in_array("hob", $result))
{
return $key;
}
}
}
Alternatively, as a dynamic function
function getKeyOfArrayContainingValue($needle, $haystack) {
foreach($haystack as $key=>$hay)
{
if(in_array($needle, $hay))
{
return $key;
}
}
}
http://php.net/manual/en/function.in-array.php
The in_array
method is useful here, we can iterate over each key/value pair and then check to see if the value of hob exists within any of those child arrays, in which case return the $key
of the child array, which we have defined in the foreach ($key=>$value
).