Hello, campers! Now then, let’s get stuck in. You can easily write a huuuuuuge article explaining iterations and how they differentiate, how to use them, etc, etc, etc. Same goes for objects and classes too. However articles like that are long winded, boring and mindless drivel but I’ll try to keep this as to the point as it gets with references to other sources where you can further your reading if that suits you…
Iterations
Some statements in programming and scripting languages are described as being iterative statements. These statements are structured and have conditions and terminating factors to control how many times the code in that block is executed. PHP has four major and commonly used iterative structures that we’ll look at now. These are:
- ‘while’
- ‘do … while’
- ‘for’
While
The while statement is probably the most basic one of the lot. It simply executes a block of code continuously looping until it’s condition is no longer met. However if the condition is never met, the code is never executed.
<?php
while (expression) {
statements;
}
?>
or…
<?php
$x = 0;
while ($x < 10) {
echo 'Variable x holds the value: ' . $x; // Note the use of the dot character to concatenate the string.
$x++;
}
?>
Do…while
With a traditional while statement the code will execute for the duration of time that it’s conditional statement is made true. With a do…while loop however the code will execute once regardless of the conditional and only loop again if it’s conditional statement is met. Always a useful tool if you want something to happen at least once…
<?php
do {
statements;
}
while (expression);
?>
or…
<?php
$x = 0;
do {
echo 'Variable x holds the value: ' . $x; // Note the use of the dot character to concatenate the string.
$x++;
} while ($x < 10) ;
?>
For
The for loop lets programmers perform a loop based on an incremental value until it reaches it’s terminating value. Unlike the while loop the variable changes as part of the condition meaning less code in the body of the loop as we no longer need to adjust this variable in the loop to help it reach it’s terminating condition.
<?php
for (initialisation; condition; increment) {
statements;
}?>
Summary
So that’s about it really! You should now understand the basics of PHP iterations and loops. All be what this post is about is pretty basic it is important to understand. My next post will be on if/else loops and case/switch statements as these have some special rules that would be a bit much to include in this post I believe. Go forth, young padawans…and iterate :)
or…
<?php
for ($x = 0; $x < 10; $x++;) { $a = $a + $b[$x]; $x++; } ><
So that’s
Responses to “Iterations in PHP”
Leave a Reply