For each loop with arrays

The creators of PHP have gone to great lengths to make the language easy to use. So, not content with the loop structures already provided, they added another one especially for arrays: the foreach…as loop. Using it, you can step through all the items in an array, one at a time, and do something with them.
The process starts with the first item and ends with the last one, so you don’t even have to know how many items there are in an array. Following example will show things :

$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;
foreach ($paper as $item)
	echo "$j: $item<br>";

When PHP encounters a foreach statement, it takes the first item of the array and places it in the variable following the as keyword, and each time control flow returns to the foreach, the next array element is placed in the as keyword. In this case, the variable $item is set to each of the four values in turn in the array $paper. Once all values have been used, execution of the loop ends.

Foreach with Associative arrays

Now let’s see how foreach works with an associative array by taking a look at following example

$paper = array('copier' => "Copier & Multipurpose",
		'inkjet' => "Inkjet Printer",
		'laser' => "Laser Printer",
		'photo' => "Photographic Paper");
foreach ($paper as $item => $description)
	echo "$item: $description<br>";

You may also like...