The for Statement PHP

Strictly speaking, the for loop is unnecessary. Any for loop can be implemented as easily as a while loop. What for offers is not new functionality, but a better structure for building the most common loops. Many loops involve incrementing a counter variable every time through the loop, iterating until some maximum is reached.

Imagine that you wanted to step through the numbers 1 through 10. Using while, you would first set a variable to be 1. Then you would make a while loop that tests if your counter is less than or equal to 10. Inside the code block you would increment your counter, making sure you do this as the last statement in the block.

The problem is that it is very easy to forget to put the increment in. The result is an infinite loop. The for loop puts all this functionality in one place. Inside the for statement you give it three things: an initialization statement, a boolean expression, and an increment statement. defines a for loop.
The for statement.
When first encountered, the initialization statement is executed. This traditionally takes the form of assigning a variable to be 0 or 1. Then, as with a while statement, the boolean expression is evaluated. If FALSE, control jumps to just after the code block. Otherwise, the code block is executed. Before the boolean expression is evaluated again, the increment statement is executed. This puts all the information needed for running the loop in one place and forces you to think about all the steps. is a very simple for loop but is typical in form.
A Typical for Loop

A Typical for Loop
Most for loops look like. They use a counter that increments by one each time through the loop. However, the for statement is not particular about what you put in the three slots. You can use more complex expressions if you wish. The initialization slot allows a comma-separated list of assignments. This can be used to assign values to two or more ariables. You may also leave a slot blank. converts the code in into a for loop. I've added line breaks to the for statement to keep the code from wrapping. It also makes it easier to see the three parts. Although the for statement is longer and looks more complicated, it really is no different from the simple example in A variable, in this case currentDate, is set to some initial value. That value is used to test for an end condition. And the value is incremented by the number of seconds in a day instead of just one.

Using for to Print Day Names

<?
/*
** print some text explaining the output
*/
print("Days left before Friday: ");
print("<OL> ");
for($currentDate = date("U");
date("l", $currentDate) != "Friday";
$currentDate += (60 * 60 * 24))
{
/*
** print day name
*/
print("<LI>" . date("l", $currentDate) . " ");
}
print("</OL> ");
?>

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics