The for each loop has to be the simplest one to understand and to use.
As the name might suggest, the idea is simple just go over every single item from the items array.
Optionally also get the key, which might be the actual key from the associative array or an index,
and get every single value and for every one of those values and optionally keys run the statements
or the actual loop body and then you are done.
So as a quick reminder we've seen arrays and the types of arrays.
I haven't explained them in depth yet but we've used arrays before.
So this is just this compound type where you have multiple items indexed by numbers starting with zero
or indexed by keys.
And they can also be Dimensional.
So let's see an example of the for each loop.
So let's see a quick example of a.
For each loop let's create a.
For each PHP file add the starting tag.
And in this example we're going to use a basket.
That would be an array associative array.
So we've seen that on the diagram before there are keys.
And keys have the values associated.
So as keys I'm going to use the things that we can have in the basket.
So I can have three apples and maybe four bananas.
And we're going to use for each to just count every single item and maybe just display how many items
of specific type someone has in a basket.
Now also keep in mind that this symbol symbol here, this arrow that are actually those two characters
placed together, it's just called ligature.
And this is a thing that I have in my editor.
So just remember those are two characters placed together.
And now we're going to count the items.
So let's use a variable called total initialized with zero.
And now the for each loop.
So we iterate over basket.
So that's the array we're gonna go over.
We use the as keyword.
And first we type the name of the variable that will represent the current key.
Then again this arrow symbol.
And then we type the variable name that will represent the current value.
So what this means is we're going to go over the basket array.
And this body inside the loop will be run for every item, which in this case is the key.
And for every quantity which is this value.
Now keep in mind that the key is optional.
This is also a valid for each loop where you're gonna skip the keys and only care about values.
Now that's sometimes the case.
In our case, we care about both.
So let me just display the count of specific item.
So I'm gonna do item equals.
Quantity.
Add a new line so the output is visible.
And I need to remember about adding to the total quantity of items.
So I can do it this way.
Either reassign total as total plus quantity or use a shorthand which would be a plus equals, which
means add the value on the right to the variable on the left.
I'm going to use this shortcut.
And finally we'll just say total items equals total.
Add a new line.
And that's it.
Now let's run PHP for each PHP.
There it is.
We've got three apples, four bananas, and seven items in total.