Pages

PHP FOREACH Loop

FOREACH is used in PHP to loop over all elements of an array. The basic syntax of FOREACH is as follows:
FOREACH ($array_variable as $value)
{
  [code to execute]
}
or
FOREACH ($array_variable as $key => $value)
{
  [code to execute]
}
In both cases, the number of times [code to execute] will be executed is equal to the number of elements in the $array_variable array.
Let's look at an example. Assuming we have the following piece of code:
$array1 = array(1,2,3,4,5);
FOREACH ($array1 as $abc)
{
  print "new value is " . $abc*10 . "<br>";
}

The output of the above code is:
new value is 10
new value is 20
new value is 30
new value is 40
new value is 50

The FOREACH loop above went through all 5 elements of array $array1, and each time prints out a statement containing 10x the array element value.

If you like this please Link Back to this article...



0 comments:

Post a Comment