Image Copy with PHP and GD
Lesson 4: Loops

This tute will use codes from Lesson 3 to show how loops can be used to simplify scripts.

A loop takes the following parameters:

$i=-50;
$count=350;
while($i<=$count){
$i=$i+50;
imagecopy($im, $red, $i, 0, 0, 0, 50, 500);
}

This code is used to place the red gradients across the back of the page. First let's look at the codes used for that part of the script.

imagecopy($im, $red, 0, 0, 0, 0, 50, 500);
imagecopy($im, $red, 50, 0, 0, 0, 50, 500);
imagecopy($im, $red, 100, 0, 0, 0, 50, 500);
imagecopy($im, $red, 150, 0, 0, 0, 50, 500);
imagecopy($im, $red, 200, 0, 0, 0, 50, 500);
imagecopy($im, $red, 250, 0, 0, 0, 50, 500);
imagecopy($im, $red, 300, 0, 0, 0, 50, 500);
imagecopy($im, $red, 350, 0, 0, 0, 50, 500);
Looking at the codes above we get the numbers for our loop.
$i=-50;This sets the beginning gradient. It will make sense in the last command. The gradient starts at 0 on the page from the left. The loop begins by adding 50 to the start and -50+50=0.
$count=350;Reading down the row of codes above from 0 to 350 for the pixels from the left, the number 350 is the end point.
while($i<=$count){The while loop tells the server that so long as the first parameter is less than the second, do something. The function is opened with a curly bracket.
$i=$i+50;This is what we want to do. Take the first number and add 50 to it until it reaches 350.
imagecopy($im, $red, $i, 0, 0, 0, 50, 500);Now put the variables in to the imagecopy code. The pixels from left is the only number that changes in this script.
}The final curly bracket, ends the function

So again our image has a row of red gradients with this loop.

CODES

The colored gradients can't be put in to a loop because they use a different image for each command line.

The white angles however can be put in to four loops. One going across the page from the left and one going across the page from the right. As well as the bottom halves of the gradients, in the same manner. This loop is a little more complicated because it is doing two things at once. Moving across the page and moving up toward the top of the page. I'll explain the concept in a loop, but I'll leave it to you to study it further and compare with the original script.
$x=25;
$y=300;
$count=150;
while($x<$count){
$x=$x+25;
$y=$y-30;
imagecopy($im, $wB180, $x, $y, 0, 0, 50, 50);
}
$x is for the pixels from the left. $y is for the pixels from teh top. Basically it is telling the server to add 25 to the left and subtract 30 from the top until $x reaches the $count. They both stop there. It is a good idea to use different names for variables in different loops on one php script because it can confuse the server if two names are the same and have different numbers.
The loops produce this image.

CODES

Putting those scripts together.


CODES
In the next Lesson I have a couple of scripts using loops for you to study and change as you wish.
LESSON 5