From the course: Learning PHP

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Working through arrays with foreach loops

Working through arrays with foreach loops - PHP Tutorial

From the course: Learning PHP

Start my 1-month free trial

Working through arrays with foreach loops

- [Instructor] Foreach loops are a little different from the other loops you've seen. They're designed specifically for traversing through arrays. So we have two types of syntax here. We have foreach array as item and then we can do something with the item or we have foreach array as key arrow value for arrays with key value pairs. Let's take a look at some examples. So on the screen we have the for loop and we're going to convert this to a foreach loop. We have our colors array defined on line two. So we could say foreach colors as color and then echo paragraph color. So now we should get two lists of colors: red, blue, green, yellow, red, blue, green, yellow. What this foreach loop is essentially saying is take each item in the colors array and assign it to the variable color one at a time, then print that color. The loop will end when there are no more elements in the array. There is much less room for error here than…

Contents