unknown os platform
Free Beginner PHP Tutorials - While loop | Whats-online.info
whats-online-info

Free Beginner PHP Tutorials - While loop


Free
2016/08/26 / Science and Tutorials

PHP while loop is a structure which tells a computer to execute a block of code while the specified condition is true. See example:-





PHP While Loop


While loop is a looping statement in PHP that executes the same block of code over and over again as long as the condition is specified. In case you are working with large data, you can use PHP loops to execute the block of code instead of adding several almost the same code-lines in a script.

Syntax

while(condition is true){     execute code }

Note that, the difference between a while loop and do.. while loop is that,  In a do..while loop, the condition is not evaluated until the end of each loop. In a while loop, the condition is evaluated at the start.
Also, in a while loop, the statement is not closed by semicolon unlike do...while loop.

Example

<?php  $sum=0; $x = 1;  while($x <= 10) {     $sum=$sum + $x;     $x++; }  echo "The sum of first ten numbers is ".$sum; ?>

Results: The sum of first ten numbers is 55 

The example above finds the sum of the first ten numbers.
First, we initialize our sum to zero to mark the first number of our sum.Then set a variable $x=1. Then, the while loop will continue to run as long as $x is less than, or equal to 10 '$x <= 10'.The sum is calculated by getting the current sum of numbers then adding the next letter each time the loop runs. $x will increase by 1 each time the while loop runs ($x++).
 
Note, the sum is outputted outside the while loop because it returns one value which is the sum of the first ten numbers.











You may also like:


Leave a comment












Subscribe to get replies direct to your mailbox

Submit comment