views:

71

answers:

4

Could some one explain me this while loop?

while (list($key, $value) = each($HTTP_GET_VARS)) {
       $get_url .= $key . '=' . $value . '&';
    }

I know its silly but many times silly things makes huge difference....

+1  A: 

each returns an array containing the current key and value, as you iterate through an array. list lets you unpack an array into multiple variables. I find the foreach construct much more clear.

foreach ($some_array as $key => $value)
{
    ...
}

As noted by Ignacio, HTTP_GET_VARS is deprecated. You can use $_GET instead.

Matthew Flaschen
Yep. This actually looks like really, really old code, like from PHP3, before foreach and $_GET existed. I wouldn't be surprised to find in some new-but-half-assed book on PHP, though.
cHao
+4  A: 

$HTTP_GET_VARS is a deprecated array that contains the parameters passed in the querystring. each() is a function that iterates through an array and returns an array consisting of the key and value of the "current" element of the array. list() is a language construct that explodes an array assigned to it into the variables passed to it.

When the end of the array is reached, each() returns a false value, causing the loop to exit.

Ignacio Vazquez-Abrams
+1  A: 

The loop goes through each of the pairs of HTTP GET parameters in the array $HTTP_GET_VARS, assigning the sides of the pair to two variables $key and $value in that order.

The assignment 'returns' its value, hence, at the end of the array, each() will return false, which despite the assignment will cause the while condition to abort.

Inside the loop, each of $key and $value are appended to the string $get_url with some formatting.

relet
+2  A: 

The each() function returns the current key and value for the given array, and then moves the array pointer (the current item) forward by one.

Therefore, calling it multiple times is a way to iterate through the items in the array in order, and when you reach the end, each() just stops returning a value.

The list() is not a function but a language construct; it's a shortcut for setting multiple variables at once. In the example posted it sets $key to the first value in the array returned by each() (the current key) and $value to the second (the current value).

There's a number of problems with that code snippet.

  1. You should reset the array pointer before you use each() like this, because you shouldn't assume that the array pointer is at the start by the time this code executes.
  2. The values it is concatenating into a query string should be escaped (eg. by urlencode()).
  3. It's also leaving a separating '&' character at the end of the query string unnecessarily.
  4. $HTTP_GET_VARS is a deprecated feature of PHP; it should be replaced with $_GET.
  5. Iterating over an array with foreach () is cleaner and easier to read than while, list, each like this, and may be faster too.
thomasrutter