|
|
 |
for loops are the most complex loops in PHP.
They behave like their C counterparts. The syntax of a
for loop is:
The first expression (expr1) is
evaluated (executed) once unconditionally at the beginning of the
loop.
In the beginning of each iteration,
expr2 is evaluated. If it evaluates to
TRUE, the loop continues and the nested
statement(s) are executed. If it evaluates to
FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is
evaluated (executed).
Each of the expressions can be empty.
expr2 being empty means the loop should
be run indefinitely (PHP implicitly considers it as
TRUE, like C). This may not be as useless as
you might think, since often you'd want to end the loop using a
conditional break
statement instead of using the for truth
expression.
Consider the following examples. All of them display numbers from
1 to 10:
Of course, the first example appears to be the nicest one (or
perhaps the fourth), but you may find that being able to use empty
expressions in for loops comes in handy in many
occasions.
PHP also supports the alternate "colon syntax" for
for loops.
User Contributed Notes
for
berndt at www dot michael - berndt de
12-Apr-2005 11:53
15-Jan-2005 06:57
Following moniarde at yahoo dot com 's idea
<?php
for ($i = a; $i!="aa" ; $i++) {
echo $i;
}
?>
will be good.
fb_mathman at hotmail dot com
02-Nov-2004 01:20
It is intersting how to use a structure that can substitue "for".
In the next lines, for instance, I create a function that get the smallest free_id for a table. It has good applications for the phpBB forum.
<?php
function assign_free_id($table, $id_field)
{
global $db;
$sql = "SELECT $id_field FROM $table WHERE 1 ORDER BY $id_field ASC";
if( !$result = $db->sql_query($sql) )
{
message_die(GENERAL_ERROR, "Couldn't get id parameters for all the elements of the table", "", __LINE__, __FILE__, $sql);
}
while ($arr = $db->sql_fetchrow($result))
{
$row[]=$arr;
}
$max_elements = count($row);
if ($max_elements==0)
{
$id= 1;
return ($id);
}
$i=1;
for ( $j=0; $j<$max_elements; $j++)
{
if ($i==intval($row[$j][0]))
{
$i++;
}
else
{
$id=$i;
return $id;
}
}
}
?>
jphansen at uga dot edu
15-Oct-2004 02:31
as harbater at teamgenesis dot com noted, don't use a comma to separate conditions in expr2. But if you do, the result will be ONLY the last condition being evaluated for the continuation of the loop. So this would iterate infinitely: for(; false, true;); and if you swapped the true and false it would break immediately.
I wouldn't count using a comma completely out of the question, since there may be a rare circumstance where you would only want to break if the last evaluation returns false.
moniarde at yahoo dot com
31-May-2004 11:06
As previously mentioned,
<?
for ($i = a; $i <= z; $i++) {
echo $i
}
?>
will print a -> z, then aa, ba, ca , etc -> yz. However, doing this:
<?
for ($i = a; ; $i++) {
echo $i;
if ($i == "z") {
break;
}
}
?>
will print only a->z. It's simple, but it works.
user at host dot com
19-Apr-2004 05:53
Also acceptable:
for($letter = ord('a'); $letter <= ord('z'); $letter++)
print chr($letter);
hayes029 at bama dot ua dot edu
05-Feb-2004 01:16
For the purposes of outputing the alphabet,
<?php
for ($i="A"; $i <= "Z"; $i++) echo "$i<br>";
?>
will actually output A-Z, then begin again with AA, AB, etc. until it finishes with YZ. Similarly,
<?php
for ($i="A"; $i <= "ZZ"; $i++) echo "$i<br>";
?>
will output A-Z, AA, AB... ZZ, then begin again with AAA, AAB, AAC... up to ZYZ.
Thus an alternative to timrosseel's example for outputting the alphabet is:
<?php
for ($i="A"; $i != "AA"; $i++) echo "$i<br>";
?>
php at project2501 dot plus dot com
15-Sep-2003 06:45
just to clarify that you can 'chain' expr1, expr2 and expr3, for instance:
<?
for($i=0 , $j=10 ; $i<5 ; $i++ , $j+=5, $k=($i+$j))
{
echo "i: $i<br />j: $j<br />k: $k<br /><br />";
}
?>
produces:
i: 0
j: 10
k:
i: 1
j: 15
k: 16
i: 2
j: 20
k: 22
i: 3
j: 25
k: 28
i: 4
j: 30
k: 34
in case you need to do more than one operation per iteration.
The reason $k does not start with a value of 10, is because expr3 ($k=($i+$j)) is evaluated at the -end- of each iteration.
bishop
17-Jul-2003 06:43
If you're into 1-liners or compact code:
<?php
implode("\n", range('a','z'));
?>
Run-times (on my boxes) are comparable to the other methods using for(). This version is (arguably) more readable than other solutions.
bishop
17-Jul-2003 03:23
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:
<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
}
?>
(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)
That's algorithmically equivalent to the common form:
<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
$val++;
}
?>
$val++ can be whatever operation you need to perform ITERATIONS number of times.
On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version: 7.9857 s
Obvious version: 27.608 s
thewhiteness at hotmail dot com
16-Dec-2002 04:10
Regarding ben's note: The reason for this is that your first example uses neither the $i++ or $i+= operators. It's like telling PHP to add nothing to it ($i+).
Another way to possibly speed a for loop would be this:
...
for (;condition;) {
// your statement/block here
}
...
This way, if you have a variable that is being updated in the body of the loop anyways, you can use it, rather than specify a number of iterations.
nzamani at cyberworldz dot de
18-Jun-2001 01:47
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
somewhat_doSomethingWith($i);
}
Faster would be:
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; $i++) {
somewhat_doSomethingWith($i);
}
And here a little trick:
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
The $i gets changed after the copy for the function (post-increment).
I don't know if
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i), $i++) ;
is correct...at least it's not really clear.
harbater at teamgenesis dot com
27-Mar-2001 08:55
If you want two conditions to be evaluated in expr2, you can't just separate them with commas like you can with expr1 and expr3.
For example, this does not work:
for ($i=$start, $count=0; $i<$total, $count<10; $i+=10, $count++)
But this does:
for ($i=$start, $count=0; ($i<$total && $count<10); $i+=10, $count++)
| |