PHP Introduction | Control Structures | Complex Repetition with for Statements
For repetition, the for statement is used more often than while. This statement can set not only a simple condition, but also initialization and post-iteration processing all at once.
for (initialization; condition; processing after each iteration) {
...... repeated processing ......
}
You can also use a colon (:) and endfor instead of braces.
for (initialization; condition; processing after each iteration):
...... repeated processing ......
endfor;
This for statement describes three elements inside the parentheses.
- The first runs before repetition starts, assigning values to variables or preparing for iteration.
- The second is the repetition condition. If the expression or value written here is true, repetition continues. When it becomes false, the loop exits.
- The third is the processing performed after the repeated block has run and before moving to the next iteration. This is “processing after each iteration.” It is mainly used to increase or decrease variable values on each loop.
Because a for statement has many parts to write, try writing it several times in practice until you become familiar with how it is used.
Look at the example below.
<?php
$total = 0;
for($i = 1;$i <= 100;$i++){
$total += $i;
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<div>
<?php echo "Total: " . $total; ?>
</div>
</body>
</html>
This rewrites the previous while sample into a form that uses for. Here, for is written as follows.
for ($i = 1; $i <= 100; $i ++) {...... omitted ......}
Before entering the loop, $i = 1 is executed and 1 is assigned to variable $i. Then the loop continues while $i <= 100 is true, meaning while $i is 100 or less. After each repetition, $i++ is executed to increase the value of $i by 1.
In this way, variable $i increases sequentially from 1 to 2, 3, and so on while the loop continues, and the loop exits when it exceeds 100.
for is more difficult than while, but using it allows you to write cleaner scripts without unnecessary code for repetition.