02 January 2011

How to use foreach to loop through php array

In php foreach is used to traverse through array variables. Sometimes you have data in array variables and you need to perform some action on this data, for this purpose you need to traverse through whole array and then perform your desired action on each element. Traversing an array can also be done using the for loop in php but it is recommended that for traversing an array foreach should be used.

Syntax

Syntax of foreach in php is as follows:
foreach ($array as $value)
{
code to be executed;
}

Where “$array” is an array variable and “$value” will contain the each element of this array one by one in each iteration.

Example

I am using a very simple example to demonstrate the use of foreach in php:
< ?php
$myarray=array(‘Bill’,’John’,’Thomas’,’Bred’,’Tom’);
foreach ($myarray as $names)
{
echo $names.”, ”;
}
?>

The output of above code will be “Bill, John, Thomas, Bred, Tom, ”.

This was a very simple example to help you understand how foreach works. For more help and explanation please feel free to comment.

Reference:

www.w3schools.com/

No comments: