'How to iterate over the keys of an array in PHP

I am trying to return an array containing the names of the people that enjoy that hobby.

Here's what I have so far:


class Hobbies
{
    private $hobbies = [];

    public function add(string $hobbyist, array $hobbies) : void
    {
        $this->hobbies[$hobbyist] = $hobbies;
    }

    public function findAllHobbyists(string $hobby) : array
    {
        return [];
    }
}

$hobbies = new Hobbies;
$hobbies->add('Steve', ['Fashion', 'Piano', 'Reading']);
$hobbies->add('Patty', ['Drama', 'Magic', 'Pets']);
$hobbies->add('Chad', ['Puzzles', 'Pets', 'Yoga']);
echo implode(',', $hobbies->findAllHobbyists('Yoga'));
php


Solution 1:[1]

public function findAllHobbyists(string $hobby) : array
{

    //create a temp array to hold all of the matching hobbyists.
    $hobbyists = [];

    //loop over each hobbyist
    foreach($this->hobbies as $hobbyist => $hobbies) {

        //if $hobby is in the $hobbyist's hobbies, add their name the temp array
        if(in_array($hobby, $hobbies)) {
            $hobbyists[] = $hobbyist;
        }
    }

    return $hobbyists;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1