Php for
From w3cyberlearnings
Contents |
for loops condition
for loops contains the initialize value, follow by the condition (check returns true or false, and check against the initialize value to a specific value), and finally the increment or decrement the initialize value. A semicolon ";" needs to separate the expression.
Syntax for loops
for(expre; expre; expre) { statement }
Example 1
<?php $list = 5; // This loop will generate the HTML header: h1, h2, h3, h4, h5 for ($i = 1; $i <= $list; $i++) { echo "<h" . $i . ">" . "Hello" . "</" . "h" . $i . ">"; } ?>
Output: HTML View Source
<h1>Hello</h1><h2>Hello</h2><h3>Hello</h3><h4>Hello</h4><h5>Hello</h5>
Example 2
<?php $count = 5; for ($i = $count; $i > 0; $i--) { echo $i . "<br/>"; } ?>
Output
5 4 3 2 1
Example 3: Generate table from array
<?php // list of the available score $score_list = array(21, 52, 12, 42, 52, 11, 42, 55, 21, 32, 13); echo "<table border=\"1\">"; echo "<tr><th>order</th><th>score</th></tr>"; for ($fo = 0; $fo < count($score_list); $fo++) { echo "<tr><td>" . ($fo + 1) . "</td><td>" . $score_list[$fo] . "</td></tr>"; } echo "</table>"; ?>
Output
order | score |
---|---|
1 | 21 |
2 | 52 |
3 | 12 |
4 | 42 |
5 | 52 |
6 | 11 |
7 | 42 |
8 | 55 |
9 | 21 |
10 | 32 |
11 | 13 |
Example 4: Generate list from multiple array
<?php $score_1 = array(89, 76, 86, 78, 99, 100); $score_2 = array(55, 78, 78, 67, 55, 79); $score_3 = array(77, 89, 100, 98, 79, 100); $score_list = array($score_1, $score_2, $score_3); for ($i = 0; $i < count($score_list); $i++) { for ($j = 0; $j < count($score_list[$i]); $j++) { echo $score_list[$i][$j] . "<br/>"; } echo "-------<br/>"; } ?>
Output
89
76
86
78
99
100
-------
55
78
78
67
55
79
-------
77
89
100
98
79
100
-------