Learning Loops in Php: Foreach

by admin Date: 11-04-2013

Loops come in several different flavors in PHP: for, while, do-while, and foreach. We will introduce you to each of them in 3 lessons and we will show you how they can making repetitive tasks straightforward and easy to maintain.

Lesson #3: The foreach Loop

To understand FOREACH loops you have to know the arrays.
When using a loop with an array, instead of having a counter that goes until proven false the FOREACH loop continues until it has used all values in the array.
So for example if an array contained 5 pieces of data, then the FOREACH loop would execute 5 times. More uses for arrays and FOREACH loops will become apparent when you start importing data from MySQL.

Foreach Loop Syntax

foreach (array as $value)  {   
//code block to be run inside loop 

On every iteration of a foreach loop, the value of the current array is assigned to $value.

Using Foreach Loop with Array

Let's imagine we want a drop down box list of our favorite browsers. We can use an array to store the names of the browsers and use PHP foreach loop in conjunction with HTML to make the drop down box. Let have a look at the code example to see how that is done.

Example 1 - Using foreach to print values in an array

$browsers = array ("Firefox", "Internet Explorer", "Opera");   
echo "<select>";   foreach($browsers as $browser)    
{    echo "<option name='$browser'>$browser</option>";   }   
echo "</select>";  

Example 2 - Using foreach to print key - values pairs in an array

<?php  $articles = array  (   "PHP Variables" => "A variable is a mean to store values such as strings or integers so we can easily reuse those values in our code...",      "PHP Strings" => "A string is a sequence of letters, symbols,    characters and arithmetic values...",      "PHP Lopps" => "In programming, we often repeat an action or a    piece of code a number of times using loops    to solve a problem..."  );    echo "<table border='1'>";  foreach ($articles as $article_title => $article_body) 
echo "<tr>";  
echo "<td>";   
echo $article_title;   
echo "</td>";    
echo "<td>";  
echo $article_body;   
echo "</td>";   
echo "</tr>";  }  
echo "</table>";   

So, in the above example we define an array of articles with key being the article title and value being the articly body. Next we use foreach loop to print the array keys and values in a table.  

Enjoy the foreach loop! 

by admin Date: 11-04-2013 hits : 955