0

I have this:

$results = array(
  'Always On' => array('alwaysOn', 'microwave'),
  'Laundry' => array('dishWasher', 'washingMachine', 'dryer'),
  'Cooking' => array('oven', 'hob', 'grill', 'kettle'),
  'Refrigeration' => array('refrigeration'),
  'Space Heating' => array('spaceHeating', 'gasBoiler'),
  'Water Heating' => array('waterHeating')
);

Now i want to search this for 'hob' and let it return 'Cooking'
How do i do that?

Wouter
  • 465
  • 2
  • 7
  • 24

2 Answers2

2

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).

Jack hardcastle
  • 2,748
  • 4
  • 22
  • 40
0

You'll need to loop through the kay => value then loop through the value to search for the value you're expecting back, something along the lines of:

<?php
$results = array(
  'Always On' => array('alwaysOn', 'microwave'),
  'Laundry' => array('dishWasher', 'washingMachine', 'dryer'),
  'Cooking' => array('oven', 'hob', 'grill', 'kettle'),
  'Refrigeration' => array('refrigeration'),
  'Space Heating' => array('spaceHeating', 'gasBoiler'),
  'Water Heating' => array('waterHeating')
);

function getRowValuesByValue(array $results, $expected) 
{
    foreach ($results as $key => $values) {
        if (in_array($expected, $values)) {
            return $key;
        }
    }

    throw new \Exception('Value not found');
}


$category = getRowValuesByValue($results, 'hob');

// Cooking
print_r($row);
LMS94
  • 1,016
  • 1
  • 7
  • 14