PHP Foreach Loop

There are many types of loops available in PHP. One of my favorite loops is the foreach loop. The foreach loop can loop through an entire array without the need to initialize an array counter. It is called a foreach loop because you get to define what you do to each loop element.

For the start of our example, we will create an array of strings that stores the number of page hits per page.M The naming convention I use for arrays is to begin the variable with ‘A_’. The array creation of ‘$A_hitsPerPage’ is shown below:

$A_hitsPerPage;
$A_hitsPerPage["index"] = "42";
$A_hitsPerPage["login"] = "12";
$A_hitsPerPage["logout"] = "13";
$A_hitsPerPage["news"] = "34";

Now that we have our array ‘$A_hitsPerPage’, we can access the various elements of the array. The syntax for the foreach loop is below:

foreach($A_hitsPerPage as $pageName => $hitCount) {
   echo "The page $pageName got $hitCount hits.<br />";
}

Though $A_hitsPerPage is required to be the array variable name, the other two variables ‘$pageName‘ and ‘$hitCount‘ can be a variable name of your choice. Just remember to replace the variable name from within the foreach curley brace accordingly. After execution of this PHP script, the page ouput looks is:

The page index got 42 hits.
The page login got 12 hits.
The page logout got 13 hits.
The page news got 34 hits.

Now you have a PHP foreach loop completely implemented with the output result. Important facts to remember about the foreach loop is that all elements will be evaluated. If you need more control, it may be helpful to consider a for loop.

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

One Response to “PHP Foreach Loop”

  1. ramki says:

    Dear sir,
    this is fine , but can you tell how to use two arrays in a single “foreach” loop.
    Thanks in advance,
    ramki

Leave a Reply