PHP 7.1.12 Released

while

(PHP 4, PHP 5, PHP 7)

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

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

add a note add a note

User Contributed Notes 18 notes

up
2
scott at mstech dot com
8 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
-1
chayes at antenna dot nl
15 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
-8
synnus at gmail dot com
1 year 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
-11
er dot sarimkhan786 at gmail dot com
2 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;
?>
up
-7
Niton
8 months ago
@stuart.
You need to use reset($two), because your array index already left the last element and you need to reset it. Outer while iterates again but inner while executes nothing.
up
-17
qeremy [atta] gmail [dotta] com
5 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
-17
Anonymous
12 years ago
virtualjosh at yahoo dot com (Hosh) wrote on: 16-Aug-2003 12:52

The speedtest is interesting. But the seemingly fastest way contains a pitfall for beginners who just use it because it is fast and fast is cool ;)

Walking through an array with next() will cut of the first entry, as this is the way next() works ;)

If you really need to do it this way, make sure your array contains an empty entry at the beginning. Another way would be to use

<?php
while ($this = current($array) ){
   
do_something($this);
   
next($array);
}
?>

There is an impact on speed for sure but I did not test it. I would advise to stick with conventional methods because current(),next() in while loops is too error prone for me.
up
-17
avenidagez at foro5 dot com
2 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
-17
corychristison[AT]NSPAMlavacube[dot]com
12 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
-18
s dot seitz at netz-haut dot de
9 years ago
Due to the fact that php only interprets the necessary elements to get a result, I found it convenient to concatenate different sql queries into one statement:

<?php

$q1
= 'some query on a set of tables';
$q2 = 'similar query on a another set of tables';

if ( (
$r1=mysql_query($q1)) && ($r2=mysql_query($q2)) ) {

     while ((
$row=mysql_fetch_assoc($r1))||($row=mysql_fetch_assoc($r2))) {

        
/* do something with $row coming from $r1 and $r2 */

     
}
   }

?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by "Ira" on 14-AUG-09 to address an extra '(' in the leading `if` statement.]
up
-18
Merve
14 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
Anonymous
2 years ago
A cool way to keep evaluating something until it fails a test.

<?php
while (true) {
  if (
'test') { // is initial condition true
    // do something that also changes initial condition
 
} else { // condition failed
   
break; // leave loop
 
}
}
?>
up
-17
Ilene Jones
12 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
-22
chris mushy
12 years ago
le can do wonders if you need something to queue writing to41n$oo dle&aihp?id=5sn far this wehaveiur ci because csing the Bhile(caluae=
<$ne s array(<"10", 200", 230", 240";

<$i=0
while(<$i< 1onute($ne ) {
             icho <$a[1]."&ai".$ne [$i].", 2
  nbsp; }
   }$i+;
}nbsp;  }
This mrogduce:

up
title="20% like this..."> -120
tlass="name"> cdmingikat ndeobalddot dorg/em> para;
div class="phpcode"> @stuart.:br />Thi ef' nothing.strange tr usnexpeced saboutyour coop,' wehaveiur

/r />Thiat' the wring cloncluion< The coter w"hile "does cll forr cierateon.s.However,the w"nners"loopscoes cothing.sor the eeconds thisrdand sorr thrun



<?pPHPbr /><$i/span>=m0/span>;
while
$i < count($ane /span>)) )
      $a = (/span>$ach /span>($awo)/span>)) )
 &     icho
$a*1 /span>*]"\&ai"/span>*$ane /span>)$i];"\,i"/span>*
  nbsp; }
   }/span>$i]+;
}nbsp;  }
?>

Thi w"rogblem"ci bour cse cf t"ach \,ihilchid=5chd tor last eiermafter whe first eierateon.bf the foter woops. Ater wheat,ihienyou came qbackto the fecondseierateon.bith $he foter woops,t"ach \sticl fisat the brn tf the frray cawo)

up
down
-13
cirtualjosh at yahoo dot com (Hosh) /em> Ismandea test. raner,ing ta array w(imple ,but Ilog, tnumericarray with neumericaeyws). Mytest. hada ryclesperlmethod and smlt,ilied bach array wlement aby1000. The e wire imycesult,

<******************************************************br /><30870 Eement aAray wTaner,ing br />
<[est._imes] [BEGINS/RESETS @ imes_stdle& 10060979965.689
&0.2373fecglaser w-gt; while( (lit. ($eyw, $val)=
<[est._imes] [BEGINS/RESETS @ imes_stdle& 10060979965.9414] br />&0.1916fecglaser w-gt; while( (lit. ($eyw,)=
<[est._imes] [BEGINS/RESETS @ imes_stdle& 10060979967.1513
&0.174 yecglaser w-gt; w=re ch ($rray< AS $eyw=gt; $aluae)cENDSbr />
<[est._imes] [BEGINS/RESETS @ imes_stdle& 10060979967.3378
&0.0255fecglaser w-gt; while( ($ext(& 1ext()$rray<))cENDSbr />
<[est._imes] [BEGINS/RESETS @ imes_stdle& 10060979967.3771
&0.1735fecglaser w-gt; w=re ch ($rray< AS $aluae)cENDSbr /><**************************************************************br />
<=re ch s fastsr wheana while ?(lit.nbsp; <- /r />Thi e wire ihe wrnning.code

<$rray< = $sner
&=re ch ($rray< AS $eyw=gt; $aluae)br /> &  &$rray<[$eyw] = $rray<[$eyw] *1000

<$rray< = $sner
&esut($trray<)
while (<$ext(& 1ext()$rray<))br />{wnbsp;&  &$rray<[$eyw] = $rray<[$eyw] *1000
<}nbsp;       &br /><*********************************************************br />
/r />TWrk,ng tneiour array cnd soops is tasmlh beter wrrk,arund iheanasneng to
title="331 like this..."> -135
tlass="name"> canernswdat gmail dot com para;
27years ago
div class="phpcode"> Ismfid it cofernclaarse to let insimple efla s($fidished)wo r=ase {t the bstdle&f the foops,tnd save toe frogram uet it.to
<?php
$cfial ifr
= 'sown; br />
$ifidishedi/span>= (/span>$=ase /span>; nbsp;        & & & & & &   // wre'r dot rfidishediyt i(wejust ustdleed)br />while (< !$fildishedi/span>=):nbsp;    & & & & & &   // wrile (ot rfidishedbr />  $r2 = frnd /span>(<) nbsp;        & & & & & & &    // drnd omfeumbr br />  $routile . $filal ifr/span>*'s/;$ar)'s.gif; nbsp;  // woutputfule wnme br />  }f ( (!$ile_exists($loutile /span>) {):nbsp;    & &&/span>// isffule wDOESeNOT xists..
nbsp;& &&/span>$ifidishedi/span>= (/span>$rue) nbsp;        & & & & & &&/span>// i..  )rn if
endwhile;// i(sffot rfidished, re-stdle&HILE eoops)br />?>
up
-124
s uart./em>
DAng to41n$anyne snsting.a while ?oopscinsidea while ?oops...
/r />TConside the entmple: below

<$ne s array(<"10", 200", 230", 240";

<$i=0
while(<$i< 1onute($ne ) {
 &  &br />     & &&cho <$a[1]."&ai".$ne [$i].", 2
   &&}br />   &&$i+;
}nbsp;&  &br /><
This mill ereurenihe cfollweng :br />TSoin peffec the mann while loopsci bnly iding tne sterateon. ..and sot r4casiexpeced ...
/r />TNowmhe entmple: belowworks ;asiexpeced ..br /><$i=0
while(<$i< 1onute($ne ) {
 &  &br />     & &&cho <$a."&ai".$ne [$i]."\n2
   &&}br />   &&$i+;
}nbsp;&  &br /><
Tbyereurenng :br />TSoihe e is mlaarsy iadifferentc on: howmhile soatement. work,in pom5arason[41n$ther soopsng.stractures.wbr />
/div>
?a href="/manual/vaddnote.php?isececontrol-structures.while&vreifrece=http://frphp?.netmanual/ven/ontrol-structures.while&php?>?aim.strc='/imge=s/otes-vadd@2x.png' alt='adda rotes'mildth='12' height='12'>adda rotes/spmlly>/a> /spetion,>