PHP Tutorial – foreach Loop

The “foreach” loop gives PHP an easy way to iterate over arrays and can only be used on arrays.

Syntax

There are two syntaxes although the second is only a minor extension of the first.


foreach ($array as $value)
{
     code to be executed;
}

The second syntax:


foreach ($array as $key => $value)
{
     code to be executed;
}

The first syntax form loops over the array given by array_expression. Every loop the value of the current element is assigned to $value. The internal array pointer is increased by one to the next element. The foreach loop runs for the all elements of an array.

The second syntax form does the same thing as the first, except that the current element key will be assigned to the variable $key. You can see that this can be useful.

foreach loop Example

Ok, let’s look at an example:


<html>
<body>

<?php
$x=array("3","2","1");
foreach ($x as $value)
{
     echo $value . "<br />";
}
?>

</body>
</html>

The output of the example will be:


3
2
1

In this second example we will use the second syntax:


<html>
<body>

<?php
$x=array("one" => 1,"two" => 2,"three" => 3);
foreach ($x as $y => $value)
{
     echo "\$x[$y] => $value.\n";
}
?>

</body>
</html>

The output of the example will be:


$x[one] => 1.
$x[two] => 2.
$x[three] => 3.

Also take a look at the other PHP language loop statements:

  • while – loop through a block of code while a specified condition is true
  • for – loops through a block of code a specified number of times
  • do…while – loops through a block of code once, and then repeats the loop as long as a specified condition is true
This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 2 responses to “PHP Tutorial – foreach Loop”

Why not let us know what you think by adding your own comment!

  1. Syed Jafar Ali Shah on November 10th, 2012:

    Excellent tutorial, really helpful in learning the basics of “foreach” loop.
    Thanks for sharing.

  2. Gauravjot on April 27th, 2014:

    Very helpful to learn foreach. Best tutorial I read yet!