Page 1 of 1

While and HTTP_POST_VARS

Posted: Sun Jul 17, 2005 9:36 pm
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?

Posted: Sun Jul 17, 2005 9:49 pm
by nielsene
Are you using

Code: Select all

reset($HTTP_POST_VARS);
before each while (...each()) loop?

Posted: Mon Jul 18, 2005 3:24 am
by onion2k

Code: Select all

foreach ($_POST as $key => $val) {
    //Don't just do something, stand there
}

Posted: Mon Jul 18, 2005 10:08 am
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.

Posted: Mon Jul 18, 2005 12:22 pm
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.