Search code examples
phpvariablesvariable-variables

Unset multiple php variable variables


I have a whole grip of variable variables that I create in a while loop from a MySQL query:

$query = "SELECT * FROM fruit_table";
$result = mysql_query($result);

//for sake of argument, well say this creates 3 rows to loop through.
while ($row = mysql_fetch_array($result)){
 $var = $row[1];
 $$var = $row[2];
}

Now we'll assume this has created: $orange = 'orange', $apple = 'red', $banana = 'yellow'. This function is going to loop back around multiple times, but I need all of the variables unset/nulled before it runs again. The variable names may be different each time based on the query that's run.

This doesn't seem to work:

unset($var);
unset($$var);

How do I go about looping though multiple variable names and unsetting all of them? Any ideas? Thanks!


Solution

  • You'll have to save the variable names that you created into an array, then unset all of them:

    $created_vars = array();
    while ($row = mysql_fetch_array($result)){
        $var = $row[1];
        $created_vars[] = $var;
        $$var = $row[2];
    }
    
    foreach( $created_vars as $var) {
        unset( $$var);
    }
    

    That being said, you should consider abandoning variable-variables, and just use an array.