The for statement in PHP

Oct 13, 2009 Author: City Hall

Thefor statement is used to create loops involving numbers. It is composedof three parts: an initialization statement, a condition, and a repetitionstatement. These three parts have important purposes within the for loop.

To find the sum of the integers from $intStart to $intEnd, you would
construct a for loop using these variables in your initial and conditional
statements, respectively.

This example demonstrate the ways that for is generally used:The following program does this:

$intStart = 1;
$intEnd = 10;
$sum = 0;
for ($a = $intStart; $a <= $intEnd; $a++)
$sum += $a;
echo '$sum,';
echo '< br>' 
echo $sum;

The output of running this program using the two values shown here,1 and 10, is

Thus, you have created the PHP-equivalent of1 + 2 + 3 + ... + 9 + 10

Or, more generally, assuming A and B are functionally equivalent tothe variables $intStart and $intEnd in the program, the sum isA + (A + 1) + (A + 2) + ... + (B – 1) + B

This whole process of summing a range of numbers is mostly of interestonly to mathematicians.

You will probably use it (or some variationof it, as the other examples show), but in the case of most sums, amore efficient calculation can be done with an explicit formula.

Depending on how efficient your program must be, and how strongyour mathematics skills are, your choice to use a for loop or to derivean explicit formula is completely up to you. (The for loop is favorablefor its simplicity.)

tags: for statement

views 3562
  1. Add New Comment