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: 57
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 23 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.
axthos commented on 8 Sep 2008 -
i gotta tell the world.
don't get it commented on 9 Sep 2008 -
I don't get it, what's so special about php foreach that a whole domain is dedicated to it? And what's wrong with http://php.net/foreach? It at least has a full explanation!
shabih commented on 22 Sep 2008 -
before reading this i don't have any idea of PHP ForEach, but after reading this i have quite a clear idea in my mind of php for each loop
thanks, well done
Manu commented on 28 Sep 2008 -
Thanks for your help
echoThis commented on 1 Dec 2008 -
you should just make this domain redirect to php.net
fetch from FORM commented on 9 Dec 2008 -
how i fetch array elements of form when it submitted
Jason D. commented on 18 Dec 2008 -
PHP for each? A noble sentiment! :)
Beatrice Achieng commented on 2 Jan 2009 -
This is nice ,but could you explain how to use foreach with multidimensional arrays also please.
Tejas commented on 7 Jan 2009 -
Wow one whole domain dedicated to foreach... You rock man.
John commented on 20 Feb 2009 -
Great! Php.net is OK, but sometimes I need things explained in simple English. Thanks!
andyhd commented on 12 Mar 2009 -
If you're going to have a domain dedicated to PHP foreach, at least make sure your explanation is correct! foreach also works with PHP Iterators, not just arrays. See http://php.net/Iterator for details.
make me money from random doamins with google adwords commented on 12 Mar 2009 -
how about stop-filling-the-net-with-useless-crap-in-a-vein-attempt-to-make-money-from-google-ad-words.com

?
WastedDomain commented on 8 May 2009 -
wait there's ads on this page? ad block plus ftw!
ziggi commented on 13 May 2009 -
I have this invalid foreach() argument from a joomla blog pluggin, any ideas would be appreciated:

Warning: Invalid argument supplied for foreach() in /home/fhlinux161/f/fluidtestsite.co.uk/user/htdocs/components/com_idoblog/assets/templates/idobloger/comment.php on line 2

First few lines of code read:


Vlad commented on 9 Jun 2009 -
Enough with the stupid comments... Get back to programming you lazy monkeys!
Gabriel commented on 25 Jul 2009 -
Can you explain a foreach whit a matrix?
lulz commented on 7 Aug 2009 -
Some day there will be a domain name FOREACH php function :P
Amit commented on 17 Aug 2009 -
Very good explaination
Devyn commented on 19 Aug 2009 -
Well, the having a whole website for a single page about a single function seems... well, overkill...
But you do a nice job of explaining everything! Good work!
echo Null commented on 23 Aug 2009 -
at least the guy who made this did successfully convinced us to visit and comment on his site... LOLs
Bhaskar commented on 1 Sep 2009 -
Thanks for providing such a wonderful tutorial.Today I have got an idea about what exactly foreach() loop does.THANKS a lot.
kanna commented on 9 Nov 2009 -
It awesome!
arun commented on 13 Nov 2009 -
its most helpfull for me thanku
Alex commented on 10 Dec 2009 -
Thank you for making this page exist. I hope this becomes a trend.
xc commented on 2 Feb 2010 -
This very good. and i think
Oisin commented on 6 Feb 2010 -
I have and error message [Invalid argument supplied for foreach()] appearing for the following line(s) of code. Any ideas?:

foreach ($results as $result)
{
if (extension_loaded('soap')) {
$totalposible = $result->totalResults;
}
else {
$totalposible = $result['totalResults'];
}
}
Mary Beth commented on 23 Feb 2010 -
How do I use a foreach and Strtoupper every other element?
I did this as a While statment and got them in a seperate arry but my assignment says Using a FOREACH function loop through the array and shift every 2nd element to upper case.

while (list($key, $value) = each($arr))
{
$svkey[]=($arr[$key 1]);
unset($arr[$key 1]);
}
Cal commented on 24 Feb 2010 -
Hello,

I am trying to understand this foreach statement. My foreach is not listing the entire array, but only the value that the pointer is on. Can someone help me.

$provinces = array("Britsh Columbia", "Alberta", "Saskatchewan", "Manitoba", "Ontario", "Quebec", "New Brunswick", "Newfoundland", "Prince Edward Island", "Nova Scotia", "Yukon", "Northwest Terriroties", "Nunavit");

foreach($provinces as $value);
{
echo "$value
";
}

I have tried sorting, and reseting the array but it still only outputs one value.

Thanks for article.
JasonHenry commented on 6 Mar 2010 -
Hi Cal.

You need to remove the (;) from your foreach().

$provinces = array("Britsh Columbia", "Alberta", "Saskatchewan", "Manitoba", "Ontario", "Quebec", "New Brunswick", "Newfoundland", "Prince Edward Island", "Nova Scotia", "Yukon", "Northwest Terriroties", "Nunavit");

foreach($provinces as $value) // (;) stops your loop
{
echo "$value";
}

OR

foreach($provinces as $value):
echo "$value";
endforeach;
Srabon.NET commented on 5 Apr 2010 -
Exactly what i was looking for :) . . Thank you :)
Roman commented on 13 Apr 2010 -
Good stuff.
no wayy commented on 20 Apr 2010 -
you bought this domain justtt to but up this tutorial? was it worth it?

I'm glad i found it
Om Prakash Sharma commented on 30 Apr 2010 -
Very Good
W3 commented on 13 Jul 2010 -
he 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).
Chris O. commented on 2 Sep 2010 -
PHP Rocks! This site rocks too! foreach() is one of the best time savers ever created. God I love the power of PHP!
Peter commented on 5 Oct 2010 -
Please explain the PHP Foreach better. I am still left confused. you basically have re-created half of what is allready easily found but made it a domain. Surely this domain name warrants a full description with examples of everything that can be done with a for each.

I.e Putting form elements from a while loop into it and submitting the form values from the loop into an sql database. That would be a good tut......