Display the contents of an array with a foreach loop

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 within it.

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

Let’s open up a new PHP tag at the end of our file. foreach statements follow a similar format to if statements, with a foreach keyword followed by an open & closed parenthesis, and then an open & closed curly bracket.

Within the parenthesis comes the array we’d like to iterate over. So this will be $tags. Next comes as, and then any arbitrary variable name for the iteration. We’ll name this $tag.

Within the curly brackets will be the code we want to execute within each iteration of the loop. This foreach tag will loop each value of the array until it has iterated over the entire array. With each pass, it will assign the value of the current iteration to our arbitrary variable name, and we will be within the context of that iteration within these curly brackets. So, it will make three passes through this foreach statement, and the first time $tag will be this ‘php’ string, the second time $tag will be equal to ‘docker’, and the third time $tag will be equal to ‘mysql’.

Let’s just echo out tag within this loop. When we refresh, we’ll see the output of our tags, but they are all squished together. This is because there are no line breaks echo’d out within our code. Since we are in an HTML file, let us concatenate a <br> tag to this echo statement, and when we refresh, we’ll now see that each of these tags is outputted on it’s own line.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
$tags = ['php', 'docker', 'mysql'];
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php
foreach ($tags as $tag) {
    echo "$tag<br>";
}
?>


Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock