By: Will
What's the purpose of programming a loop? Why would I need to do this on my website?
In this article, we will look at a use case for loops on your website.
We'll keep it relatively simple here. There are many use cases for programming a loop. One of the most common cases is to display the contents of an array into pre-built blocks for your website.
The example we will use here is an image gallery where you can add a new element by simply writing a single line for each image.
<?php
$Array = array(
'1' => array('image.jpg', 'Some content'),
);
foreach ($Array as $i => $item) {
echo '<div class="card">';
echo '<div class="image"><img src="'.$Array[$i]['0'].'"></div>';
echo $Array[$i]['1'];
echo '</div>';
}
?>
This loop is called a foreach loop in PHP. So what exactly is going on here? Let's break this down a little bit.
We are using a nested array in the $Array variable. This will allow us to attach a key (for this first example, this is the '1' value) to the contents of our gallery cards.
Following the key, we have the inner array with two values, the first containing the image file and the second containing some explanation content.
Next, we'll use a foreach loop to loop through each key (with the contained values) to display a new card with your predefined styling. The loop will echo the necessary divs while filling in the image file and explanation content for each given value.
Once you've got this in place, updating your gallery with a new image is as simple as typing the following line.
'2' => array('new.jpg', 'Here is somemore content!'),
Ensure you update the key value. In this case, it's '2'. I chose to use increasing numbers for this example, but you can use anything you'd like. For example, this could be your image title.
This is simply one example of what you can do with a loop. Using loops will save you a lot of headache and time updating your website in the future, and they're quite easy to implement.
The same principle described here can be used to output more than just a gallery. For example, you could implement this idea as part of your website navigation or display a list of news articles.
With this new understanding of loops, see what you can come up with to make your site easier to maintain!