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.

5
  • 1
    ${'_'.$val} = $resultVal; ... other examples: stackoverflow.com/questions/9257505/… Commented Jan 19, 2019 at 20:35
  • 2
    Why not use arrays? Commented Jan 19, 2019 at 20:36
  • Or yeah, use an array ;) Cleaner, safer. Commented Jan 19, 2019 at 20:37
  • Possible duplicate of PHP Variable Variables to set a number as part of a variable name Commented Jan 19, 2019 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. Commented Jan 19, 2019 at 20:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.