Home > Tutorials > PHP Tutorials > FOR and FOREACH Loops

FOR and FOREACH Loops

Much like WHILE loops FOR and FOREACH loops are meant to enable the repeated execution of a section of code. However, unlike while statements, for and foreach have features built into them to update the sentinel value for every repetition. So lets go back for a moment to our original example in the WHILE loops tutorial – Bart Simpson having to write “I will not pledge allegiance to Bart.” 50 times on the blackboard. Here is our original code for this:

bart-simpson-while-loops-php-rapid-purpleNow we are trying to make things easier for Bart Simpson right? So let’s take a look at how we can use a FOR loop to really simplify things even further. See right now our code isn’t necessarily wrong – but if our page get’s much more complex than it is now things won’t be easy to read. Furthermore any developer that’s going to come in after us won’t have the easiest of times figuring everything out – especially if you’re initialization variables ($x and $times) aren’t specified directly above the while loop.

So let’s rewrite this with the use of a FOR loop:

<?php
for ($i = 0; $i <= 50; $i++)
{
echo "I will not pledge allegiance to Bart. "; 	
}
?>

Given the formatting – we’ve just taken our code down from 6 line to 4 – and compressed everything together so that any developer can come in later on and know exactly what variables are associated with what loop.

The first part of the for loop is called the initialization statement. This is executed only once, at the very beginning of the loop. Next, before the code block is executed, the conditional expression is checked to make sure it is true. After the code block has been executed, and before the conditional expression is evaluated again to begin another repetition of the loop, the repetition statement is executed.

Let’s consider another example. Imagine we had an array consisting of people’s names and ages. A memberlist of sorts. And we wanted to neatly display this data. We could utilize a FOR loop to loop through our array and display the appropriate data in a specified format.

<?php
$membersArr = Array("John Smith", 39, "Wendy Stevens", 28, "Bob Baker", 39 );

for ($x = 0; $x < count($membersArr) - 1; $x += 2)
{
echo $membersArr[$x] . ', ' . $membersArr[$x + 1]; // Displays John Smith, 39 (each on a new line)
echo '<br>';
}
?>

The elements 0, 2, and 4 of the array are our members’ names. So, $x starts at 0 and increases by 2 for every repetition of the loop. To get each person’s age, we use $x + 1. The loop terminates when the condition, $x < count($membersArr) –1, becomes true. This condition becomes true, in this case, when $x is 4. count() returns 6 because there are 6 elements in the array; however, we subtract one from that, giving us 5, and have used the less than sign (<) instead of the less than or equal to sign (<=), so the last index used is actually 4. Now in the real world you're member list will probably come to you in the form of an associative array instead of the simple array we used for the above example. This is where the FOREACH loop comes into play. The FOREACH statement is similar to FOR in that it is basically a specialized form of the WHILE loop. FOREACH, however, unlike FOR, is intended to be used specifically with arrays. So let’s see how we would handle an associative array with a FOREACH loop:

<?php
$membersArr = Array("John Smith" => 39, 
		    "Wendy Stevens" => 28, 
		    "Bob Baker" => 39 );


foreach ($membersArr as $name => $age)
{
echo $name . ' - ' . $age . '<br>'; // Displays John Smith - 39 (each on a new line)
}
?>

The syntax for FOREACH takes two forms: a basic usage to retrieve only each value in an array, and a second usage to retrieve key/value pairs from an associative array. This makes it possible to not only retrieve each value from an array, but also have the value’s key. The key, in this instance, being the members age.

With a simple, non associative array, things are just as easy:

<?php
$membersArr = Array("John", "Wendy", "Mike" );
foreach ($membersArr as $name)
{
echo $name . '<br>'; // Displays each name on a new line
}
?>

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

Top 5 Community Builder Platforms of 2017

Even though the world is pretty set on social networks, what with Facebook, Twitter, LinkedIn, ...

Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.

Close