0

On a simple foreach loop that is generating variables variables, how can I add an underscore after the $ in the variable? The variable names are coming from the names of the columns in a table and are being populated by the single entry being fetched.

// Fetch values
$sqlVal = "SELECT * 
            FROM tablename 
            WHERE ID=$PostID";
$rowVal = DBConnect($sqlVal, "Select", $siteDB);

// Create variable variables from table column names and populate with value
foreach ($rowRow as $val=>$resultVal) :
    if (is_string($val)) :
        $$val = $resultVal;
    endif;
endforeach;

echo "test: $ValName";

The test result above works but I want it to be $_ValName with the underscore but I can't seem to work out how to achieve that.

DonP
  • 725
  • 1
  • 8
  • 27
  • 1
    `${'_'.$val} = $resultVal;` ... other examples: https://stackoverflow.com/questions/9257505/using-braces-with-dynamic-variable-names-in-php – IncredibleHat Jan 19 '19 at 20:35
  • 2
    Why not use arrays? – Andreas Jan 19 '19 at 20:36
  • Or yeah, use an array ;) Cleaner, safer. – IncredibleHat Jan 19 '19 at 20:37
  • Possible duplicate of [PHP Variable Variables to set a number as part of a variable name](https://stackoverflow.com/questions/29571861/php-variable-variables-to-set-a-number-as-part-of-a-variable-name) – miken32 Jan 19 '19 at 20:44
  • Thank you, I knew it had something to do with squiggly-brackets but couldn't work out the syntax. Giving what I need now. As for using an array, that's what DBConnect() does - creates an array of values from the database entry but unable to use assoc with it as it breaks many other things across five sites that share it. – DonP Jan 19 '19 at 20:49

0 Answers0