0

I have a column named what with values like this:
earth sun sea sky ...

I need to create php variables named as this values and give to that variables the same values.

for example:

$earth = 'earth';
$sun = 'sun';
...

I tried:

$st = $db->prepare("select what from bdef");
$st->execute();
while ($row = $st->fetch()) {
    ${$row['what']} = $row['what'];
}

echo $earth;

Result: Unknown variable...

  • 1
    This sounds an awful lot like an [X-Y problem](http://xyproblem.info/) to me. Why do you need to dynamically create variables with such specific names? It is answered [here](https://stackoverflow.com/questions/9257505/using-braces-with-dynamic-variable-names-in-php), but as several people mention in the comments there: why would you ever need to do this? – Loek Aug 22 '18 at 08:34
  • @Loek, because I have over 20 values and need 20 variables, and trying to make the code shorter. –  Aug 22 '18 at 08:38
  • 1
    Would it not be better to put them in an array – RiggsFolly Aug 22 '18 at 08:38
  • 1
    Maybe you could retrieve the database records as an array and use that? – Stuart Wagner Aug 22 '18 at 08:39
  • 1
    @puerto if all you need is to echo the variable, you might as well `while ($row = $st->fetch()) { echo $row['what']; }` or as the other suggested, save everything into an array and use that later on. – Loek Aug 22 '18 at 08:40
  • 2
    And this code should work (tested) – AymDev Aug 22 '18 at 08:40

1 Answers1

0

just use extract In my example code I used a function, just to keep it all contained within the scope of the function without stray global variables in your namespace.

function dostuff($row) {
  extract($row);
  echo $earth;
}
$st = $db->prepare("select what from bdef");
$st->execute();
while ($row = $st->fetch()) {
    dostuff($row);
}
Tschallacka
  • 27,901
  • 14
  • 88
  • 133