PHP FOREACH Loop



PHP Tutorial > PHP Commands > 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.

Next: PHP INCLUDE




Copyright © 2013   1keydata.com  All Rights Reserved.  Privacy Policy


PHP Variables
PHP Operators
PHP IF ELSE
PHP ELSEIF
PHP Switch
PHP While Loop
PHP FOR Loop
PHP DO WHILE Loop
PHP FOREACH Loop
PHP INCLUDE
PHP Functions
PHP ARRAY
PHP FORMS
PHP Cookies
PHP Redirect
PHP MySQL

PHP Syntax

PHP Sitemap

PHP Resources