views:

92

answers:

4

I found this PHP code in an app I have to modify...

$links = mysql_query($querystring);
foreach (mysql_fetch_array($links) as $key=>$value) 
{
    $$key = $value;
}

I'm a bit stumped.

Is it really iterating over the query results and copying the value into the key?

If so, what would be the point of this?

Also, what is the double $$ notation? I've not seen this before in PHP and I can't seem to find reference to it on the PHP site. Is it a typo? It doesn't seem to be affecting the code. I don't want to go "fixing" anything like this without understanding the consequences.

+4  A: 

The $$ isn't a typo; it's how you interact with a variable named by another variable. Like if you do

$varname = 'foo';
$$varname = 'bar';

you've just set $foo to 'bar'.

What the loop is doing is expanding the row contents into the current variable namespace, kind of like extract(). It's a terrible way to do it, not least because it's also iterating over the numeric indices.

chaos
Thanks for that. Exactly what I needed to know :)
nedlud
+2  A: 

You generally see that written like this.

$links = mysql_query($querystring);
while ($row = mysql_fetch_array($links)) 
{
    echo $row['id'];
}

The $$ is what's called a variable variable.

It looks like it's essentially making the keys as vars holding the value. Sort of what register_globals does to the POST/GET etc vars. I wouldn't recommend doing it this way. I dare say it will lead to problems, like overwriting vars, and unexpected vars being available.

alex
+1  A: 

It's creating key-value pairs based on the sql query results and result structure.

As for the $$, it's just another variable, except this time it's the result that's set to a variable.

$key = "hello";
$$key = "hi";
echo $key;

output is: "hi"

Sev
+1  A: 

The $$ will reference the variable with the name stored in the first variable. So for example:

$var='some';
$some=15;
echo $$var;

That will print 15. It takes $vara and gets 'some', so then it takes that as a variable name because of the second $ and it prints the value of $some which is 15.

So basically that code is copying the values into a variable that has the same name as the key.

Tom Kiley