While and HTTP_POST_VARS

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

While and HTTP_POST_VARS

Post by Mr Tech »

When I have two of these on the page

Code: Select all

while(list($key, $val)=each($HTTP_POST_VARS)) 
 { 
	 $a++;
etc...
Only the first one works... Both are very similar but all the $ are different except the $HTTP_POST_VARS.

Any ideas on what's wrong?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

Are you using

Code: Select all

reset($HTTP_POST_VARS);
before each while (...each()) loop?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Code: Select all

foreach ($_POST as $key => $val) {
    //Don't just do something, stand there
}
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

~onion2k's approach is much cleaner (and a much more accepted way of doing what you want).

There's also an important difference. Foreach() loops use their own internal array pointer. Each() doesn't. So, when looping through using foreach(), the loop essentially makes a copy of the array, then loops through the copy - leaving the original alone. Each() actually works on the original array and advances that array pointer. So, after you've gone through the array once with each(), the pointer is at the end. Any further each() calls will fail.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

Yes, I prefer the "new" foreach construct. However, there are times when people might have to still use the "old fashioned" for (stuff=each($array)) style. And when using that style you have to remember to use reset.
Post Reply