Sample PHP Code: PHP For Loops, Foreach, While and Do While

There are different PHP loops: PHP for loops, foreach, while, and do while loops. There are advantages and disadvantages to each type of PHP loop (depending on the scenario), and it is beneficial to understand how to work with them.

This PHP sample code should help you get a basic familiarity with creating and using PHP loops.

Earlier this week we learned how to create PHP variable variables. In several PHP samples that were used on this site, we used loops in the code. I thought it was time to put together a basic tutorial on PHP loops.

PHP For Loop

PHP for loops are great when you need to run a PHP loop a certain number of times based on an incrementing number. The loop is based on a conditional check done at the beginning of the PHP loop. As long as the condition is true (which is the middle section), the loop will continue on.

<?php
for($num=1; $num <= 10; $num++)
{
	echo "Number: $num<br />";
}
?>

$num=1 defines the initial value of the $num variable (which is executed when the loop first starts). $num <= 10 is the conditional statement that runs the loop and $num++ is what happens to the variable on each iteration of the loop (in this case it increments $num by one). Just as long as the conditional statement is true, the loop will keep going.

Here is a brief breakdown on how the PHP For Loop functions in the above example.

  1. The PHP variable $num is created and assigned the value of 1.
  2. $num is checked to see if it is less than or equal to 10. If it is, it goes inside the PHP loop (what is between the curly brackets).
  3. We print text to the screen (line #4).
  4. PHP goes back up to line #2 and increments $num by one. It then checks to see if $num is less than or equal to 10. If it is, it continues on with the loop. If $num is 10 or more, it stops the PHP for loop and continues processing the PHP code after the loop.

With arrays that use number based keys, you can use count() or sizeof() to go through the array using a PHP for loop. However, when working with arrays, the PHP foreach loop is preferable (IMO).

PHP Foreach Loop

The PHP foreach loop was designed specifically for arrays. It doesn’t matter whether the key is numeric or not, it can handle all PHP arrays.

<?php
$teams = array(
	'team1' => 'Cowboys',
	'team2' => 'Broncos',
	'team3' => 'Bulls'
);

foreach($teams as $teamNum => $teamName)
{
	echo "$teamNum: $teamName<br />";
}
?>

If you specify the $teamNum => $teamName….it will assign each “row” in the array. The key value will go to $teamNum and the value will go to $teamName. You could just use $teamName instead, but then you wouldn’t have access to the key in each row (but sometimes you don’t care about the key).

If you need to go through an array, than use the PHP foreach loop. You don’t have to mess with resetting the array and the PHP code is simpler.

PHP While Loop

Like the PHP for loop, the PHP while loop runs off of the expression being true. The conditional check happens before the loop starts. I personally prefer using the PHP while loop when going through the results of a database query.

<?php
$query = mysql_query('SELECT * FROM table1') or die('Query error: ' . mysql_error());

while($array = mysql_fetch_array($query))
{
	extract($array);
	// all of the columns in table1 are now PHP variables
	// ...
}
?>

Line #4 is not only checking a conditional statement, but it also is assigning a variable (in this case it is getting a row from the database results). You can use whichever conditional statement you want to use.

Line #6 is a method for extracting an associate array, where the keys of the array become PHP variables. This can be incredible handy and save a lot of code, but just be careful when using this. You could unintentionally override values.

PHP Do While Loop

The PHP do while loop is similar to the while loop, except the expression is checked at the end of the loop. I never use this loop, but it is good to be aware on how it works.

<?php
$count = 0;

do
{
	$count++;
	echo "$count<br />";
} while($count < 10);
?>

You can use the break; statement in all PHP loops to stop the loop from processing. This can be useful if certain values generated by a loop trigger the loop to stop processing.

Do you have any preferences in which PHP loop you use in certain scenarios?

17 thoughts on “Sample PHP Code: PHP For Loops, Foreach, While and Do While

  1. while($array = mysql_fetch_array($query))

    I did not really understand this code until I learned about boolean functions in C++. The reason why this works in a while loop is because while the function is not at the end of the database records (end of file), the mysql_fetch_array function returns true. Once it reaches end of file, it returns false. This enables you to perform and operation AND have it be a condition.

    Like

    • That is a good description. A lot of things about programming and PHP I didn’t really understand until I started using them a lot. This is how I learned OOP. This is one element that I know I would have got a much sooner grasp on if I went to college for programming.

      Like

    • Your description is close but not entirely 100% accurate. For someone who is using type comparison, this will make a big difference to you. In this code, mysql_fetch_array returns an array of result set items in a key=>value pair, where the keys are the column names and the values are the column values. When MySQL reaches the end of the resultset, mysql_fetch_array returns NULL, not false. It will return false in a failure condition.

      The best way to look at it is as follows:
      In PHP, the use of the assignment operator (equals sign) creates an implied function. By assigning mysql_fetch_array to the variable $array, you are requesting a return value of whatever is left in $array after the assignment. Because you just assigned it, this will be whatever is returned from mysql_fetch_array.

      When mysql_fetch_array finds a result, it returns a key=>value pair of the row, in a boolean sense this evaluates to true. When it’s done with the resultset, it returns null, which evaluates to false. This is why the look breaks when the result set is done.

      Just something to keep in mind if you’re wondering why mysql_fetch_array !== false…

      Like

  2. PHP For Loops, Foreach, While and Do While…

    There are different PHP loops: PHP for loops, foreach, while, and do while loops. There are advantages and disadvantages to each type of PHP loop (depending on the scenario), and it is beneficial to understand how to work with them….

    Like

  3. I have found that with DB queries, I get ~12% better performance using a do…while loop. IE:

    $sql = ‘SELECT * FROM `myTable`’;
    $qry = mysql_query($sql) or die(‘Doh!’);
    $cnt = mysql_num_rows($qry);

    if($cnt > 0)
    {
    do
    {
    $row = mysql_fetch_assoc($qry);
    // code here..
    }while(–$cnt > 0);
    }

    Like

    • I would assume this is because your comparison condition is using integers instead of the return value from mysql_fetch_assoc. Try this instead:

      if ( $cnt > 0 ) {
      while ( $cnt– > 0 ) {
      $row = mysql_fetch_assoc( $qry );
      }
      }

      I would be curious to see what happens.

      Like

  4. One thing I know is that you skip the first check in a do..while loop.. But that one check I doubt would be the full reason.. So I not 100% sure why do…while is bit faster than while..

    Like

  5. That is a good description. A lot of things about programming and PHP I didn’t really understand until I started using them a lot. This is how I learned OOP. This is one element that I know I would have got a much sooner grasp on if I went to college for programming.

    Like

  6. EllisGL, I cant see exactly why do while is faster, but the only possible difference is the jump prediction in architecture’s code instruction set. e.g. the processor can suppose that the condition for a while loop is going to be true, so it feeds the instructions after the conditional jump and starts running them in the first stages of the instruction pipeline, saving a couple of pipeline stages. Besides that, be aware that $cnt++ and –$cnt may not have the same performance too.

    Like

  7. so how do you output asterics instead of numbers using any of the loops? e.g instead of 1 u get * 2 u get ** and so on

    Like

  8. i have four columns in one table and 2 column in the second table.two of the columns are common for both table..I am using array using the following code:

    $res1 = mysql_query(“SELECT * from test”);////Test table
    echo “”;
    while($r = mysql_fetch_array($res1))
    {
    echo “”;

    $res2 = mysql_query(“SELECT * from test2”);////Test table
    echo “”;
    while($r1 = mysql_fetch_array($res2))
    {
    echo “”;
    //echo “$r1[0]”;
    //echo “$r1[1]”;
    print_r($r1[0].””.$r1[1].””);
    echo “”;
    }

    print_r($r[0].””.$r[1].””.$r[2].””.$r[3].””);
    echo “”;
    }

    How can i compare to find the mached values?please help me.Thankyou in advance

    Like

Comments are closed.