Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Sometimes we only want SOME of the objects in the collection. Enter filters. This is another piece of functionality or method to add to our collection class.
Array Functions
There are more advanced array functions that we could use to filter our array as well.
Array Map
Example:
$titles = array_map(
function ($recipe) {
return $recipe->getTitle();
},
$this->recipes
);
Array Filter
Example
$taggedRecipes = array_filter(
$this->recipes,
function ($recipes) use ($tag) {
return in_array(ucwords($tag),$recipes->getTagArray());
}
);
Okay, we're starting to get somewhere.
0:00
Now I want to be able to pull only
the recipes with a particular tag.
0:02
Let's go back to our recipe collection.
0:07
We'll create a new method
called filterByTag.
0:15
We'll pass in the value of
the tag that we want to look for.
0:25
We'll initialize a new
taggedRecipes array.
0:30
Then we can loop through the recipes and
look for our tag.
0:40
We can use if in_array, we're going to
make sure that our tag is lowercase.
0:55
We use strtolower.
1:02
And our tag.
1:06
Then we'll be looking
in the recipe getTags.
1:09
If we find the tag, we'll add
this recipe to our taggedRecipes.
1:17
Finally, we'll return our taggedRecipes.
1:33
Let's go back to our cookbook and
use our new filter.
1:39
I'm going to create
a new recipe collection.
1:45
This is going to be for
any recipe tagged breakfast.
1:48
Then we can loop through the breakfast
recipes after we filter by tag.
2:08
Here's our filter.
2:15
And we pass it breakfast.
2:20
Then we'll return each of these as recipe.
2:24
Then we're going to add this recipe
to our breakfast collection.
2:31
Now let's render our
breakfast recipes instead.
2:43
Now we see just the recipes
that were tagged as breakfast.
2:55
There's one more feature that I'd
like to see for our collection.
2:59
A shopping list.
3:02
We'll dive into that in the next video.
3:03
You need to sign up for Treehouse in order to download course files.
Sign up