Understanding Foreach in PHP
by Abu Aisyah on Feb.05, 2010, under Ngoprek, PHP, my notes
This tutorial is an easy way to understand the foreach. Yes, this is for the newbie confused with foreach. Foreach usually used in the variable loops which it has an array value. Array values are such as result from a database, or array value like this.
$ array = array ( ‘January’, ‘February’, ‘March’, ‘April’, ‘April’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘ December ‘);
How do these values can occupy each row in a table? Of course the easiest is to use foreach. Although could also use while. But I prefer to use foreach, because the value of the array can we count on. In addition, more cut script when using foreach.
To use the foreach example is as follows:
<? php foreach ($ array as $ value) ( echo "$ value <br>"; ) ?>
What does the above coding?
You have the variable $ array. Which of any value you define the variable $ value. The variable $ value is what the future will bring the value of $ array was the only one. Each $ value actually has the key. These keys are not visible in the foreach above because by default the key is a sequence of zero to the number of array-1. Suppose you have an array value as above. There are 12. So his array keys like this:
array ( [0] => 'January', [1] => 'February', [2] => 'March', [3] => 'April', [4] => 'May', [5] => 'June', [6] => 'July', [7] => 'August', [8] => 'September', [9] => 'October', [10] => 'November', [11] => 'December' )
numbers in bracet is array keys. If you want to display the keys array, then foreach his form is like this:
<? php foreach ($ array as $ key => $ value) ( echo "[$ key] => $ value <br>"; ) ?>
Variable $ key is useful to display the array key. Suppose you want to be featured odd key only. So can the following manner:
<? php $ array = array ( 'January', 'February', 'March', 'April', 'April', 'June', 'July', 'August', 'September', 'October', 'November', ' December '); foreach ($ array as $ key => $ value) ( if ($ key% 2 == 1) echo "$ value \ n"; ) ?>
The result should be like this:
February
April
June
August
October
December
That’s my little understanding about foreach for you, newbie in PHP. I hope this tutorial can help a little. Good Luck!




