Search code examples
phpsqlvariable-variables

What is this loop using PHP $$ syntax doing?


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.


Solution

  • 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.