Introduction to PHP while loops

24 March 2009| One Comment| Print

This is just a quick introduction for beginners getting started with PHP and using while loops. You will quickly find that while loops are used regularly to cycle through specific data.

So here’s a little code snippet of a simple while loop in action.

<?php
$number = 0;
while ($number <= 10)
{
echo $number;
$number++;
}
?>

Lets run through the code to see whats happening. we start by using a php delimiter tag to declare that we are using php script. all your php code needs to be wrapped in these tags. e.g. <?php ‘code goes here’ ?>. The next line we’re setting the variable $number and giving it a value of ’0′, we then set the while loop and in the brackets set the ‘while clause’ in our case we’re saying that while $number is less than or equal to 10 then do whats in the curly brackets. In the brackets we’re just echoing the variable $number and after that we re-set the value of $number adding one to it.

If you want to increase a number by one each time simply put ++ after the variable. for example.

<?php
$i=2;
$i++;
echo $i;
?>

in the example above $i will be 3.


There are many uses for while loops, this is a basic introduction for those who are new to php. If you have any questions or comments please leave them below.

demo


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

One Comment

  • Rocky

    $query = mysql_query(“SELECT * FROM `my_table`”);

    while($row = mysql_fetch_assoc($query)){
    echo $row['value'];
    }

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here