PHP while Loop

The while loop is typically used when the number of iteration is unknown or random. For example, flipping a coin until you get heads may take only 1 try or it might take 100 tries. The number of tries is unknown.

$coin = 1;
while( $coin ) { 
  // randomly choose a number between 0 and 1
  $coin = rand(0, 1);
  echo "$coin <br>";
}

While loops are often used in conjunction with reading a record set from a database query or reading the contents of a text file. As long as PHP is able to continue fetching records from the record set or reading lines from the text file then the loop continues. As soon as the function fails then the loop stops. You can also put a break command inside the loop, wrapped in an if statement. The break command will force PHP to exit from the loop.