1. 23
    Display the contents of an array with a foreach loop
    1m 56s

Display the contents of an array with a foreach loop

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Iterating, or looping over an array is very easy with PHP's foreach loop.

Instructor: [0:00] Arrays aren't too useful by themselves, so they are usually used in combination with a loop, also known as an iterator. These loops iterate through every value within an array, so you can do something with it.

[0:12] The most common type of loop statement in PHP is a foreach statement. This iterates through all records of an array, no matter how many there are.

[0:21] Let's open up a new PHP tag at the end of this file. Foreach statements follow a similar format to if statements with a foreach keyword, followed by an open and closed parentheses, and then an open and closed brackets.

[0:38] Within the parentheses comes the variable that we'd like to iterate over, so this will be tags. Next comes an as keyword, and then any arbitrary variable name for the iteration. We'll name this tag. Within the curly brackets will be the code that we want to execute within each iteration of the loop.

[0:59] This foreach loop will loop through every single one of the values within this tag's array. The first iteration will be PHP, the next will be Docker, and MySQL, and each one of those iterations will be assigned to the tag variable name. Within this foreach loop, we will be within the context of the iteration.

[1:20] Let's just use an echo tag within this loop and we will echo out the tag. Let's go ahead and save this and see how this looks. We'll see all of these words squished together and it looks like one word. This is because there are no line breaks echoed out within our code, and this is just outputted in an HTML file.

[1:42] Let's go ahead and concatenate on a <br> tag to add a line break of HTML. When we refresh this page, we will now see that each of these tags is outputted on its own line.