Use an array key to determine current iteration

Creating our list of tags, we only defined the values of the tags. Even though we did not explicitly define them, keys also exist within arrays.

If we don’t define them, keys are created for us automatically, and they are zero-based which means they start at 0. So, the first value in this loop, ‘php’, has the key of 0, the second one has a key of 1, the third has the key of 2, and so on.

We can access the key within a foreach loop by passing it as the first value after as. This can be assigned any arbitrary variable name again, but it’s common to name this $key. Then before our $tag variable is defined, we will place an equal greater than operator. This is an operator that is commonly used with arrays.

Then, let’s add our $key to the echo output, followed by a colon.

<?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 $key => $tag) {
    echo "$key: $tag<br>";
}
?>

When we refresh our page, we’ll see the evidence of our zero-based array.

It’s easier to remember this format of “array as key then value”.

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