PHP for Loop
The for
loop - Loops through a block of code a specified number of times.
The PHP for Loop
The for
loop is used when you know in advance how many times the script should run.
Syntax
for [init counter; test counter; increment counter] {
code to be executed for each iteration;
}
Parameters:
- init counter: Initialize the loop counter value
- test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
- increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
Try it Yourself »
Example Explained
- $x = 0; - Initialize the loop counter [$x], and set the start value to 0
- $x
Try it Yourself »
Example Explained
- $x = 0; - Initialize the loop counter [$x], and set the start value to 0
- $x
Try it Yourself »
The following example will output both the keys and the values of the given array [$age]:
Example
Try it Yourself »
You will learn more about arrays in the PHP Arrays chapter.
PHP program to print table of a number:
The below program prints table of a number using a loop. The PHP echo statement is used to output the result on the screen.
ExampleDOCTYPE html>
Output
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 9 * 10 = 90
Please Share
How do you use a loop in a table?
Algorithm. Step 1: Enter a number to print table at runtime. Step 2: Read that number from keyboard. Step 3: Using for loop print number*I 10 times. // for[i=1; iChủ Đề