Archive for July 2009

How to use While Loop in PHP

Friday, July 03, 2009 · Posted in

This is a tutorial on how to use a while loop in a PHP. The output will be the same if you were going to use a for loop, the only difference is only the code itself and especially the concept of each loop and how this loop performs its action when the programmer run his/her program. Below is a sample illustration on how to code while loop in PHP.

PHP Code:

<?php
$var_x = 1;
while($var_x <= 5)
{
echo "Number: ".$var_x."<br/>";
$var_x++;
}
?>
From the given codes above as you can observe we really put the PHP opening tag and at the end also we put the PHP ending tag, so that every time we execute the program it would not return any error. Because sometimes programmers for got to put the opening and closing tags that might be the cause of some errors sometimes in a application. After the opening tag we initialized our variable with the value of one. So, now the variable $var_x has now a value of 1. Then on the next line is the while loop itself, inside the while loop we put variable again and this time we put an operator to determine of the value is less than or equal with 5 only. Next is to print the value of the variable and after is to increment our variable. The purpose of $var_x++ is to increment the value of the variable each time the loop executes until it reach the desire value which is 5. Regarding with the open and close braces you can omit it but it is mostly required especially if you are following some coding standards but it is recommended that you have to put braces for you to be able to know where does your statement starts and ends. Below is the sample output of the above code.

Sample Output:
You can try this with your own. If there are some comments or questions about this article just CLICK THIS LINK to be redirected to the forum page.

Powered by Blogger.