Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Spencer Bigum
Spencer Bigum
3,250 Points

This is how you use the filter function for OOP PHP collections, but whats the difference from using foreach?

I also added a fix to return multiple items instead of just one item, but what is the difference from using a foreach loop instead?

FILTER EXAMPLE

$taggedRecipes = array_filter(
            $this->recipes,
            function ($recipes) use ($tag) {
                $tags = $recipes->getTags();
                return array_filter($tags, function ($item) use ($tag){
                    $exploded = explode(",", $item);
                    return in_array($tag, $exploded);
                });
            }
        );

FOREACH LOOP EXAMPLE

$taggedRecipes = array();

        $recipes = $this->getRecipes();

        foreach ($recipes as $recipe){
            foreach ($recipe->getTags() as $recipeTags){
                $exploded = explode(",", $recipeTags);
                if(in_array($tag, $exploded)){
                    $taggedRecipes[] = $recipe;
                }
            }

        }