PHP 8.0.0 Release Candidate 1 available for testing

while

(PHP 4, PHP 5, PHP 7)

Циклы while являются простейшим видом циклов в PHP. Они ведут себя так же, как и в языке C. Простейшей формой цикла while является следующее выражение:

while (expr)
    statement

Смысл выражения while очень прост. Оно указывает PHP выполнять вложенные выражения повторно до тех пор, пока выражение в самом while является TRUE. Значение выражения expr проверяется каждый раз перед началом цикла, поэтому даже если значение выражения изменится в процессе выполнения вложенных выражений в цикле, выполнение не прекратится до конца итерации (каждый раз, когда PHP выполняет выражения в цикле - это одна итерация). Если выражение while равно FALSE с самого начала, вложенные выражения ни разу не будут выполнены.

Также, как и с оператором if, вы можете группировать несколько выражений внутри одного цикла while, заключая эти выражения между фигурными скобками или используя альтернативный синтаксис:

while (expr):
    statement
    ...
endwhile;

Следующие примеры идентичны, и оба выведут числа от 1 до 10:

<?php
/* пример 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* выводиться будет значение переменной
                   $i перед её увеличением
                   (post-increment) */
}

/* пример 2 */

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

add a note add a note

User Contributed Notes 12 notes

up
-5
scott at mstech dot com
10 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
-20
avenidagez at foro5 dot com
5 years ago
Is strange that the manual states...
"Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. "

Because it can't be SOMETIMES

If it behaves that way, then it is a bug, because it ALWAYS must not run the nested statement(s) even once if the WHILE expression evaluates to FALSE from the very beginning.

Another way to exit the while loop is by using the BREAK statement.. see it in the manual.

And if expression evaluates to NULL is the same as FALSE
while (expression evals to NULL){ }
up
-28
chayes at antenna dot nl
18 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
-29
synnus at gmail dot com
4 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
-25
ravenswd at gmail dot com
10 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
-25
Merve
17 years ago
This is an easy way for all you calculator creators to make it do factorials. The code is this:

<?php
$c
= ($a-1);
$d = $a;
while (
$c>=1)
{
$a = ($a*$c);
$c--;
}
print (
" $d! = $a");
?>

$a changes, and so does c, so we have to make a new variable, $d, for the end statement.
up
-23
Ilene Jones
15 years ago
For Perl programmers, break is similar to last

while (1) {
   while(cond) {
       if (error) {
           break 2; // in perl this could have been last;
       }
   }
}
up
-27
corychristison[AT]NSPAMlavacube[dot]com
15 years ago
While can do wonders if you need something to queue writing to a file while something else has access to it.

Here is my simple example:

<?php

 
function write ($data, $file, $write_mode="w") {
   
$lock = $file . ".lock";
    
// run the write fix, to stop any clashes that may occur
   
write_fix($lock);
    
// create a new lock file after write_fix() for this writing session
   
touch( $lock );
    
// write to your file
   
$open = fopen($file, $write_mode);
   
fwrite($open, $data);
   
fclose($open);
    
// kill your current lock
   
unlink($lock);
  }

  function
write_fix ($lock_file) {
    while(
file_exists($lock_file){
     
// do something in here?
      // maybe sleep for a few microseconds
      // to maintain stability, if this is going to
      // take a while ?? [just a suggestion]
   
}
  }

?>

This method is not recommended for use with programs that will be needing a good few seconds to write to a file, as the while function will eat up alot of process cycles.  However, this method does work, and is easy to implement.  It also groups the writing functions into one easy to use function, making life easier. :-)
up
-26
mattbacq2004 at gmail dot com
1 year ago
<?php

$i
= 50; // number of loops

/*

the variable can
be modified:              $i

*/

while(!$i ==0){
   
DoAnyFunction();
}
up
-34
qeremy [atta] gmail [dotta] com
8 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
-32
nickleus at gmail dot com
2 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
-36
er dot sarimkhan786 at gmail dot com
4 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