for루프는 PHP에서 제일 복잡한 루프이다. C와 똑같은 방식으로 동작한다. for루프의 문법은 다음과 같다:
for (expr1; expr2; expr3)
statement
첫번째 표현식(expr1)은 루프의 시작에서 바로 조건없이 평가된다 (수행된다).
각 반복(iteration)의 시작부분에서 expr2이 평 가된다. 이 표현식이 TRUE이면 루프는 계속되고 내포된 구문(들)이 수행된다. FALSE이면, 루프 수행을 멈춘다.
expr3표현식은 각 반복의 끝부분에서 평가된다 (수행된다).
각 표현은 비어있거나 콤마로 구분한 여러 표현을 가질 수 있습니다. expr2에서, 콤마로 구분한 표현은 모두 평가되지만 결과는 마지막 부분에서만 가져옵니다. expr2이 비어있다는 것은 루프가 무제한 수행되어야 한다는 것을 의미한다 (PHP는 C처럼 TRUE로 인식) 이런 기법은 생각처럼 필요없지는 않다. 왜냐 하면 종종 for문의 표현식 대신에 break문으로 루프를 끝낼 필요가 있기 때문이다.
다음 예제 코드들을 보세요. 이 코드 모두 1부터 10까지의 숫자를 출력한다:
<?php
/* 예제 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* 예제 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* 예제 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
물론, 첫번째 예제(혹은 네번째) 코드가 가장 좋은 방법이다. 그러나 for루프에서 빈 표현식을 사용해야 하는 경우도 부딪히게 될것이다.
PHP는 for루프에 대한 대체 "콜른 문법"을 지원한다.
for (expr1; expr2; expr3):
statement
...
endfor;
많은 사용자가 아래 예제처럼 배열을 탐색합니다.
<?php
/*
* 이 배열은 루프를 도는 동안
* 변경할 데이터를 가지고 있습니다.
*/
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863),
);
foreach do-while
--------------------------------------------------------------------------------
Last updated: Fri, 24 Jul 2009
add a note User Contributed Notes
for
kanirockz at gmail dot com
21-Mar-2010 07:49
Here is another simple example for " for loops"
<?php
$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero
for($i="0"; $i<strlen($text); $i=$i+1){
if(substr($text,$i,1)==$searchchar){
$count=$count+1;
}
}
echo $count
?>
this will be count how many "e" characters in that text (Welcome to PHP)
kanirockz at gmail dot com
21-Mar-2010 07:48
Here is another simple example for " for loops"
<?php
$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero
for($i="0"; $i<strlen($text); $i=$i+1){
if(substr($text,$i,1)==$searchchar){
$count=$count+1;
}
}
echo $count
?>
this will be count how many "e" characters in that text (Welcome to PHP)
Steven
11-Jan-2009 06:50
Alternating form rows:
Changing $rows will change how many columns are in a row.
dkimbel13 at gmail dot com
07-Jan-2009 11:41
Just a note on looping through an array using the for() loop.
with the array...
<?php $array = array("value1","value2","value3"); ?>
is the equivalent of...
<?php
for($i=0;$i<count($array);$i++){
echo("Element $i contains $array[$i]<br/>");
}
?>
I don't know if there is any advantage, just thought I would mention it. http://badluck.tv
24-Mar-2008 01:05
Nested For Loop with the same iterator as the parent.
(Well formatted so the resulting code is clean when executed).
Useful for outputting a data array into a table, ie. images.
<?php
//Dummy data
$data = array(73,74,75,76,78,79,80,81,82,83,84,85,86,87);
//Our 'stepping' variable
$g = 0;
//Our rowcount
$rowcount = 0;
echo "<table cellspacing='0'>\r";
for ($i=0; $i<count($data); ) {
echo "</table>\r";?>
eduardofleury at uol dot com dot br
14-Jun-2007 01:18
<?php
//this is a different way to use the 'for'
//Essa é uma maneira diferente de usar o 'for'
for($i = $x = $z = 1; $i <= 10;$i++,$x+=2,$z=&$p){
$p = $i + $x;
print "\$i = $i , \$x = $x , \$z = $z <br />";
}
?>
lishevita at yahoo dot co (notcom) .uk
08-Sep-2006 07:33
On the combination problem again...
It seems to me like it would make more sense to go through systematically. That would take nested for loops, where each number was put through all of it's potentials sequentially.
The following would give you all of the potential combinations of a four-digit decimal combination, printed in a comma delimited format:
Of course, if you know that the numbers you had used were in a smaller subset, you could just plunk your possible numbers into arrays $a, $b, $c, and $d and then do nested foreach loops as above.
- Elizabeth
JustinB at harvest dot org
04-Aug-2005 11:23
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can. Although many have stated this fact, most have not stated that there is still a way to do this:
<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
// Do Something with All Those Fun Numbers
}
?>
user at host dot com
19-Apr-2004 10:53
Also acceptable:
<?php
for($letter = ord('a'); $letter <= ord('z'); $letter++)
print chr($letter);
?>
bishop
17-Jul-2003 08: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:
$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
nzamani at cyberworldz dot de
18-Jun-2001 06: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: