<< PHP For Loop | PHP Tutorials | PHP Do While Loop >>

PHP Foreach Loop

The foreach loop is very similar to other loops as it... well... loops through stuff :P But to go into more detail, it is used specifically to loop through arrays (both non-associative and associative). It can be very useful in situations where you don't know what data you'll be dealing with (such as data from a database).

Foreach Loop Syntax

Since we are using arrays in the foreach loop, it will not stop until it has completed going through the array,or you stop it but we won't talk about that just yet :P The syntax is as follows:

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

The $array_variable can be any variable containing an array. The $key will be the variable that will contain the current 'key' to the value. The $value will actually hold the value of the current array item we are going through. In some cases, you will not need to know the $key, and you can save a little bit of typing by using this syntax:

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

That will not give you any $key to deal with and just give you the value. This could be useful when working with non-associative arrays.

How to Use the Foreach Loop

Say that you owned a store and you wanted to list how many books, pets and tools you sold that day. You could use the foreach loop to accomplish this. We will set an array with the keys being the name of the product category, and the values being the number sold that day:

<?php
$products_sold = array('Books' => 12, 'Pets' => 5, 'Tools' => 25);
echo 'Products Sold<br />';
foreach ($products_sold as $product_name => $number_sold) {
echo "{$products_name}: {$number_sold}<br />";
}
?>

This is what the end users will see:

Products Sold
Books: 12
Pets: 5
Tools: 25

Now if you wanted to just display the products that are offered there, there would be no need for the $key so we can get rid of it:

<?php
$products_sold = array('Books', 'Pets', 'Tools');
echo 'Products Sold Here<br />';
foreach ($products_sold as $product_name) {
echo "{$product_name}<br />";
}
?>

This is what the end users will see:

Products Sold Here
Books
Pets
Tools

You should note that the foreach loop will loop through the items in the order in which they are set.

<< PHP For Loop | PHP Tutorials | PHP Do While Loop >>