Page 192 - CITS - Computer Software Application -TT
P. 192
COMPUTER SOFTWARE APPLICATION - CITS
The for loop - Loops through a block of code a specified number of times.
Syntax
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iterarion
• expression3 is evaluated after each iterarion
Example:
Print the numbers from 0 to 10:
Example Explained
1 The first expression, $x = 0;, is evaluated once and sets a counter to 0.
2 The second expression, $x <= 10;, is evaluated before each iteration, and the code block is only executed if
this expression evaluates to true. In this example the expression is true as long as $x is less than, or equal to,
10.
3 The third expression, $x++;, is evaluated after each iteration, and in this example, the expression increases
the value of $x by one at each iteration.
PHP for each Loop
The for each loop - Loops through a block of code for each element in an array or each property in an object.
The for each Loop on Arrays
The most common use of the foreach loop, is to loop through the items of an array.
Example:
Loop through the items of an indexed array:
For every loop iteration, the value of the current array element is assigned to the variable $x. The iteration
continues until it reaches the last array element.
179
CITS : IT&ITES - Computer Software Application - Lesson 47 - 62