Display the contents of an array with a for loop
We’ve previously used a
foreach loop to display the contents of an array, but we can also use a
for loop. This has a bit of a weird syntax and is a bit more complex, but gives you some extra flexibility including a built-in counter, and the ability to exit out of a loop based on that counter value or another condition.
Let’s replace our call to
var_dump with a new PHP block. We’ll start our new
for loop, and open up our parenthesis. For loops accept three parameters: a counter, condition, and incrementer.
Our counter will be a regular PHP variable. For some reason, it’s common practice to use an
$i for counters, probably just because it’s easier to type, and perhaps it stands for “increment”. We’ll start this with a value set equal to 0. This is to account for arrays being zero-based indexes, meaning that the first key of array always starts with 0.
Our parameters are separated by semicolons. The next one is a condition. We’ll set this equal to
$i < $numPosts. So, this will execute for however many posts we have, and no more. Finally, we need to iterate this counter, so we will set this to
$i++ to add a value to the
$i variable on every iteration.
<?php for ($i = 0; $i < $numPosts; $i++): ?> <?php endfor ?>
We can use our curly brackets again, but one thing I didn’t mention previously when we used a
foreach loop is that we also have access to the alternate syntax. Just like
endif, we can use an alternate syntax named
foreach to make things easier to process when dealing with outputting data within a loop. We can use
endforeach to end the
foreach loop, and we can also use
endfor to end a
Within this loop we can now output values from our
$posts array. Let’s create an h3 tag and use a PHP echo tag to output
$posts. Remembering that we can reference arrays directly by their index, we can reference this
$i variable that will initially be equal to 0, which is the first record of our posts array. And we can tack on another set of brackets to access properties within this array index, so we can call the
title to output it.
We’ll do the same thing for
content, but output it within a
<?php $title = 'My Blog'; $posts = [ [ 'title' => 'How to learn PHP', 'content' => 'This is how you learn PHP.', ], [ 'title' => 'How to learn MySQL', 'content' => 'This is how you learn MySQL.', ], ]; $numPosts = count($posts); $postDisplay = $numPosts === 1 ? 'post' : 'posts'; $numPostsDisplay = "$numPosts $postDisplay"; ?> <h1><?= $title ?></h1> <h2><?= $numPostsDisplay ?></h2> <?php for ($i = 0; $i < $numPosts; $i++): ?> <h3><?= $posts[$i]['title'] ?></h3> <p><?= $posts[$i]['content'] ?></p> <?php endfor ?>
And when we refresh the page, we’ll see our data being outputted from the array.