Who's Online
We have 7 guests onlineBreadcrumbs
| For Loop |
PHP Looping - For Loop
Loops execute a block of code a specified number of times, or while a specified condition is true.
The for loop is used when you know in advance how many times the script should run. The for loop is the most complex loop in PHP but maybe it is the most used as well. In case of for loops you makes the loop variable initialisation, conditional check, loop variable update in a single line Syntax: for (expresion1; condition; expresion2){ code to be executed; }
This syntax requires a bit more explanation. Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).
Example: The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: Code: <html>
An output will be: The number is 1
The last loop structure in PHP is the foreach. This is a special loop as you can use it only for arrays. The goal of the foreach loop to iterate over each element of an array. If you try to use it with a normal variable you will get an error. The foreach loop is used to loop through arrays. Syntax:
Example: The following example demonstrates a loop that will print the values of the given array: Code:<html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html> An output will be: one
|