PHP: foreach

The PHP control statement, foreach{}, is a handy way to cycle through the elements of an array and perform the same operations on each. Foreach{} only works with arrays (both numerical and associative).

PHP Foreach Syntax

foreach (array_expression as $value) statement

Array_expression: This is the array whose elements we want to process.

Value: This is the variable we want to assign the element to during each loop.

Statement: These are the instructions we want to perform during each iteration of the loop.

In the case of an associative array, the syntax can also look like this:

foreach (array_expression as $key => $value) statement

In this case, $key is assigned the associative element's key from the array.

How to Use Foreach Loops in PHP

Pretend we have the following array:

$namearray[0] = 'Barry'; $namearray[1] = 'Bob'; $namearray[2] = 'Bill';

If we wanted to echo each of these names in turn, we could use a foreach{} loop:

foreach ($namearray as $value) echo $value;

This will cycle through the array, and echo the data contained in $value (which will be each name).

Leave a comment
Name:

Comment:

 
Total comments: 21
Michael commented on 16 Nov 2006 -
Very nice and simple. Well done. Thanks
Kris commented on 1 Jan 2007 -
Thanks, this finally is starting to make some sense
Name commented on 5 Jan 2007 -
Wow, a whole domain for a single PHP statement? To each his own, I guess...
NightShift58 commented on 29 Jan 2007 -
Do you guys plan on doing phpswitch.com as well. I know someone who might be interested...
Esteban commented on 5 Feb 2007 -
I need help, I dont know how to exclude some words of the array, I have this:

$Array = (explode(" ",$copete));

foreach($Array as $key) {
$keywords = strtolower($key);
print "$keywords,";

}

I need to exclude for example: "to, from, etc".
Thanks.
Monkeyman commented on 12 Mar 2007 -
Esteban, I have no clue if you'll check this, but here's how to do it:

$Array = (explode(" ",$copete));
foreach($Array as $key) {
$exclude = array("to","from");
$keywords = strtolower($key);
if(!in_array($keywords,$exclude)){
echo $keywords . ",";
}
}


I havn't checked it, but unless I made some stupid error, that will work.
dumbo commented on 24 Apr 2007 -
I'm impressed at how your explanation of $key => $value does not manage to
explain anything except to people who already know what it does! "$key is assigned
the associative elemet's key" is utterly lacking in meaning unless you bother to explain
what "associative" and "key" mean.

Nice work!
Beginner commented on 28 Apr 2007 -
How does the loop know what $value refers to? Is it automatically defined by positioning it after "as"? Or do you have to declare it in some way before you use it there?
another beginner commented on 29 Apr 2007 -
Beginner: yes, it's automatically defined
ben commented on 30 Apr 2007 -
how to do multiple foreach loop?

foreach ($namearray, $addressarray, $telarray as $value)

something like that?
Rbn commented on 10 May 2007 -
I'm doing a foreach to display several lines:

foreach ($movies as $movie_id => $title)

I would like that each line has a different colour depending of a value in the database (if this row is A=Red, if the row has the value B=Blue).

How can I do that?

Thanks :-)
Pete commented on 15 May 2007 -
Hi,

I have this foreach loop

foreach ($_SESSION['qty'] as $k => $p) {
if (isset($_SESSION['qty'][$p])) {
echo "I would like $p x {$_SESSION['product'][$k]} please.";
}
}

For some reason {$_SESSION['product'][$k]} will not write when in the loop but is getting picked up outside the loop.

Any body see what's going wrong here?

any help would be great
lol commented on 2 Jun 2007 -
I don't know why you would dedicate a whole website on foreach loops.

I think he is just trying to experiment how the site will do he ahs some plans to monetize this site to make millions ;p
Ben commented on 29 Dec 2007 -
This is one of the weirdest sites i have ever encountered.
meinhard commented on 10 Mar 2008 -
nice site with a clear purpose. now we are waiting for phpif.com and phpwhile.com! ;)
Charlie commented on 24 Jun 2008 -
I think you have the right idea here in your explanation but to jazz it up a bit and for those less experienced, you might want to show the result of each of the FOREACH statements using the example array. May I also suggest something here to show how powerful the FOREACH statement can be, in place of the numeric index, use some letters as your index. In this way, you can show how the $key => $value can work to their advantage. Just some ideas here. For example in your array, replace the [1] with [abc] and the [2] with [def]. Then the foreach($namearray as $key => $value) would return upon using the echo command: abc & def...Thanks...
Dean commented on 27 Jun 2008 -
considering you are using a whole domain just for this i think you could have gone a little bit deeper into it
Stan commented on 4 Jul 2008 -
I have a quiz site. And i want to iterate through every entry in the mysql tabel and respond according to whether the choice of the user was correct or not
Rocky Romano commented on 10 Jul 2008 -
Very Good explanation...with the execption of the associative array. Where is the example of that?
Mattings commented on 11 Jul 2008 -
Hey guys, check out this really cool site that explains this and loads of PHP stuff really well: http://www.php.net/foreach

(nice link farm btw)
dan commented on 28 Aug 2008 -
dumbo is right. if you dedicated a domain to it at least come up with a good explanation.