Introduction
The for() function is an iterative function. The word iteration is basically a posh word for looping. You use looping to avoid spaghetti code, and generate a list of output without having to type it all manually. For example, a looping function, for() can be used to loop the 10 times table without having to type it all out manually. Of course, there are much more practical uses for for(), but this tutorial is to tell you how to use this function so you can integrate it into your own projects.
The function
for() loop is used to loop for a set number of iterations. The function takes the following syntax. The following syntax illustrates the function using pseudo code.
Code: [hide]
Code: [show]
for ( initialize a counter; conditional statement; increment a counter)
{
do this code;
} 'initialize a counter' is used to set a start value for the loop. For example, we want to stop looping from the value 0, we set the initialisation counter as 0. 'conditional statement' is used to set a stop value for the loop. This is usually in the form of a conditional statement or in the form of a set value. Thinking about it as a stop value, we can set this to 10. 'increment a counter' is used to set the amount to increment each iteration. For example, we could set the for() loop to increment + 2 each iteration, or + 1 each iteration (in which cause you would use ++ operand). Example Code
The following is an example use of for().
Code: [hide]
Code: [show]
$num = 10;
for ($i = 0; $i <= $num; $i++)
{
echo $i;
} The above code will increment +1 each iteration, from a start value of 0 to a stop value of 10. On each iteration $i is echoed. The second parameter 'conditional statement' can take many forms such as sizeof($bla) and count($bla).
Optimisations
In the previous section, it was mentioned that you can use different forms (thus functions) in the second parameter 'conditional statement'. Bearing this in mind, the function is called each iteration, thus slowing your procedure down. Therefore, on larger looping structures, consider determining the size of the stop value before the loop or consider using something like below:
Code: [hide]
Code: [show]
for ($i = 0, $size = sizeof($bla); $i < $size; $i++)
{
echo $i;
} In the above code, the size of $size is determined within the function, but still only calculated once.
Summary
To conclude, the for() loop is an iterative function of which we know how many iterations to be executed and carried out by the program code.
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment