Hrvatski

printer friendly version

Loops

One of the key features of any programming language is to automatically generate content. If there are certain tasks you want to be repeated during the script execution, you don't have to write them many times - for() and while() loops can do it instead.

for() loop

The basic code is this:

<?php
	for($i = 0; $i < 100; $i++) echo '!';
?>

This loop will print 100 exclamation marks. The first expressin in the bracket, $i = 0; says that variable $i will have an initial value of 0. The second expression, $i < 100; means that the loop will continue as long as $i is smaller that 100. The third expression, $i++ determines what should happen with variable $i in the meantime - and in this case, variable will increase its value by one after each step.

So, here is a similar example:

<?php
	$x = 0;
	$y = 100
	for($i = $x; $i < $y; $i++) echo '!';
?>

It does just the same as the example before, but it's more general - all we have to do is change the values of $x and $y and the loop will work in another domain. Now, let's work on something more concrete.

Let's say you have an avatar gallery. You often update it, so adding them to your HTML page manually can be tedious. And there certainly is an easier way to do it.

In order to make updating more automatic, the image names should be generic. This means they should not be ppgavatar.gif, inuyasha-avatar.jpg, cgarts01.gif... but something like avatar1.gif, avatar2.jpg, avatar3.gif... So only the index changes.

<?php
	$last = 25;
	for($i = $last; $i > 0; $i--) {
		$avatar = 'images/avatars/avatar'.$i.'.gif';
		echo "<img src=\"$avatar\" alt=\"avatar ID: $i\" /> ";
	}
?>

Before the loop, you determine which avatar is the newest. The loop will go from the newest to the oldest added, since the value of variable $i will be decreased by 1 after each step.

Its obvious that the above example works only for GIF files. Also, you may delete some avatars after a while from the folder, so you'll have X-s instead of images. Very easily we can achieve that it works for both GIF and JPG files, plus it will work only if the image exists.

<?php
	$last = 25;
	for($i = $last; $i > 0; $i--) {
		$avatar = 'images/avatars/avatar'.$i;
		if(file_exists($avatar.'.gif')) $avatar .= '.gif';
			else $avatar .= '.jpg';
		if(file_exists($avatar)) echo "<img src=\"$avatar\" alt=\"avatar ID: $i\" /> ";
	}
?>

I think it's pretty much straight-forward what the function file_exists() does. If the file with extension .gif exists, we'll add this extension to the avatar path. Otherwise, we will add the .jpg extension to the path. Once again we check if the file exists, if it does then the image will be shown, otherwise it just skips to another image.

So, that's basically all you need for your simple avatar gallery :) Just update the variable $last to the last added avatar each time.

while() loop

While loop is pretty similar. As the word describes, while a condition is satisfied, the loop will work. Let's try adapting the avatar gallery using this loop.

Now, let's assume you don't feel like editing the avatars.php page every single time you upload an avatar, but you are sure you will never delete an old avatar, so they will follow eachother without any gap. I know this sounds unrealistic, but it's just for demonstration - you will surely find this type of loop very helpful, especially in combination with MySQL databases, which I use all around this website.

So, here's our code:

<?php
	$i=1;
	while (file_exists(images/avatars/avatar'.$i.'.gif') || file_exists(images/avatars/avatar'.$i.'.jpg') ) {
		$avatar = 'images/avatars/avatar'.$i;
		if(file_exists($avatar.'.gif')) $avatar .= '.gif';
			else $avatar .= '.jpg';
		echo "<img src=\"$avatar\" alt=\"avatar ID: $i\" /> ";
		$i++;
	}
?>

The first line is your first avatar's ID. Then, in the next line we check if avatar with that ID exists (with any of the possible extensions). If it does, the loop is played once, displaying the avatar. Last line of loop increases the avatar ID, so the next time loop is played, it will check the next avatar in the row. In case avatar does not exists, we assume all existing avatars are shown, so the loop is finnished. Neat, huh? You never ever need to update your avatars page again.

But wait, what if I delete an avatar?, I hear you say. Well, there is another way. This is a little advanced, but very very neat. Our next block of code will look through the entire folder and load all images that exist inside all by itself.

<?php
	$path = 'images/avatars';
	$folder = dir($path);
	while($avatar=$folder->read()) {
		if($avatar == "." || $avatar == "..") continue;
		echo '<img src="'."$path/$avatar".'" alt="avatar" /> ';
	}
?>

If the folder is empty, nothing will happen. If there are images in the directory, they will be displayed. All you need to do is upload images to the folder, and the avatars page will refresh automatically.

Made your pages dynamic yet? Go ahead, it will save you a lot of trouble.


Share this tutorial with your friends!





Branding & web design by Nela Dunato

Facebook