while

while는 PHP에서 제일 간단한 루프형이다. C와 똑같은 방식으로 동작한다. while문의 기본적인 형태는 다음과 같다:

while (expr)
    statement

while문의 의미는 단순하다. while 표현식이 계속 TRUE이면, PHP에게 내포되어있는 구문(들)을 반복 수행하도 록 하라는것이다. 표현식의 값은 루프의 시작에서 매번 체크가 된다. 그래서 이 표현식 값이 내포된 구문(들)의 수행동안에 바뀔지라도 반복(iteration) 의 끝이 아니면 수행은 끝나지 않게 된다.(루프에서 PHP가 구문을 한번수행 할때 한번 반복(iteration)이다) 시작된지 얼마안되어 while표현식이 FALSE로 판명되면, 내포된 구문(들)은 즉시 수행을 멈출것이다.

if문과 마찬가지로 중괄호나 대체문법을 사용하여 구문의 그룹을 둘러쌈으로써 while루프 안에 여러 구문을 그룹화할 수 있다.

while (expr):
    statement
    ...
endwhile;

다음 예는 모두 동일하다. 둘다 1부터 10까지의 숫자를 출력한다:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* 출력하는 값은 증가하기
                   전의 $i입니다.
                   (post-increment) */
}

/* example 2 */

$i 1;
while (
$i <= 10):
    echo 
$i;
    
$i++;
endwhile;
?>

add a note add a note

User Contributed Notes 9 notes

up
2
Dan Liebner
3 years ago
While loops don't require a code block (statement).

<?php

while( ++$i < 10 ); // look ma, no brackets!

echo $i; // 10

?>
up
-9
mparsa1372 at gmail dot com
3 years ago
The example below displays the numbers from 1 to 5:

<?php
$x
= 1;

while(
$x <= 5) {
  echo
"The number is: $x <br>";
 
$x++;
}
?>

This example counts to 100 by tens:

<?php
$x
= 0;

while(
$x <= 100) {
  echo
"The number is: $x <br>";
 
$x+=10;
}
?>
up
-30
scott at mstech dot com
14 years ago
Just a note about using the continue statement to forego the remainder of a loop - be SURE you're not issuing the continue statement from within a SWITCH case - doing so will not continue the while loop, but rather the switch statement itself.

While that may seem obvious to some, it took a little bit of testing for me, so hopefully this helps someone else.
up
-41
synnus at gmail dot com
7 years ago
<?php

// test While Vs For php 5.6.17

$t1 = microtime(true);
$a=0;
while(
$a++ <= 1000000000);
$t2 = microtime(true);
$x1 = $t2 - $t1;
echo
PHP_EOL,' > while($a++ <= 100000000); : ' ,$x1, 's', PHP_EOL;

$t3 = microtime(true);
for(
$a=0;$a <= 1000000000;$a++);
$t4 = microtime(true);
$x2 = $t4 - $t3;
echo
PHP_EOL,'> for($a=0;$a <= 100000000;$a++); : ' ,$x2, 's', PHP_EOL;

$t5 = microtime(true);
$a=0; for(;$a++ <= 1000000000;);
$t6 = microtime(true);
$x3 = $t6 - $t5;
echo
PHP_EOL,' > $a=0; for(;$a++ <= 100000000;); : ' , $x3, 's', PHP_EOL;

//> while($a++ <= 100000000);   = 18.509671926498s
//
//> for($a=0;$a <= 100000000;$a++);  =  25.450572013855s
//
//> $a=0; for(;$a++ <= 100000000;);  =  22.614907979965s

// ===================

//> while($a++ != 100000000); : 18.204656839371s
//
//> for($a=0;$a != 100000000;$a++); : 25.025605201721s
//
//> $a=0; for(;$a++ != 100000000;); : 22.340576887131s

// ===================

//> while($a++ < 100000000); : 18.383454084396s
//
//> for($a=0;$a < 100000000;$a++); : 25.290743112564s
//
//> $a=0; for(;$a++ < 100000000;); : 23.28609919548s

?>
up
-40
ravenswd at gmail dot com
14 years ago
I find it often clearer to set a simple flag ($finished) to false at the start of the loop, and have the program set it to true when it's finished doing whatever it's trying to do. Then the code is more self-documenting: WHILE NOT FINISHED keep going through the loop. FINISHED EQUALS TRUE when you're done. Here's an example. This is the code I use to generate a random filename and ensure that there is not already an existing file with the same name. I've added very verbose comments to it to make it clear how it works:

<?php
$finaldir
= 'download';

$finished = false;                       // we're not finished yet (we just started)
while ( ! $finished ):                   // while not finished
 
$rn = rand();                          // random number
 
$outfile = $finaldir.'/'.$rn.'.gif';   // output file name
 
if ( ! file_exists($outfile) ):        // if file DOES NOT exist...
   
$finished = true;                    // ...we are finished
 
endif;
endwhile;                               
// (if not finished, re-start WHILE loop)
?>
up
-44
nickleus at gmail dot com
6 years ago
<?php
$i
= -1;
while (
$i) {
    echo
$i++;
}
?>
outputs  "-1" then stops because "0" (zero) gets evaluated as FALSE.

this demonstrates why it's important for a PDO statement fetch-ing a column value inside a while-loop to test explicitly for FALSE.
up
-47
qeremy [atta] gmail [dotta] com
11 years ago
Instead of this usage;

<?php
$arr
= array("orange", "banana", "apple", "raspberry");

$i = 0;
while (
$i < count($arr)) {
  
$a = $arr[$i];
   echo
$a ."\n";
  
$i++;
}
// or
$i = 0;
$c = count($arr);
while (
$i < $c) {
  
$a = $arr[$i];
   echo
$a ."\n";
  
$i++;
}
?>

This could be more efficient;

<?php
while ($a = $arr[1 * $i++]) echo $a ."\n";
?>
up
-51
chayes at antenna dot nl
22 years ago
At the end of the while (list / each) loop the array pointer will be at the end.
This means the second while loop on that array will be skipped!

You can put the array pointer back with the reset($myArray) function.

example:

<?php
$myArray
=array('aa','bb','cc','dd');
while (list (
$key, $val) = each ($myArray) ) echo $val;
reset($myArray);
while (list (
$key, $val) = each ($myArray) ) echo $val;
?>
up
-50
er dot sarimkhan786 at gmail dot com
8 years ago
simple pyramid pattern program using while loop
<?php
$i
=1;
while(
$i<=5)
{
   
$j=1;
    while(
$j<=$i)
    {
      echo
"*&nbsp&nbsp";
     
$j++;     
    }
    echo
"<br>";
   
$i++;
}
?>
// or alternatively you can use:
<?php
$i
=1;
while(
$i<=5):

   
$j=1;
    while(
$j<=$i):
      echo
"*&nbsp&nbsp";
     
$j++;     
    endwhile;
   
    echo
"<br>";
   
$i++;
endwhile;
?>
To Top