Search code examples
phpvariablesevaluate

PHP: how do i properly evaluate a nested variable variable in a loop?


ok. here's the basics:

for ($k=1;$k<3;$k++) {
  ${'var'.$k} = 'foo';
} // so far so good

for ($j=1;$J<3;$j++) {    
  $dbq .= "stuff {$var{$k}} ";
} // problem here ^^  ^^

i'm looking for $dbq to render out to "stuff foo stuff foo". but i'm not sure how to do this. i can SET the variable in a loop no problem, but i don't know how to evaluate it out in a loop correctly. PHP explodes when i try this. i need the VALUES of the variable variable. and its not even a true "variable variable" since there's no real referencing going on; not trying to mislead, i just don't know what else to call it...

and if there's a better way to do this, then by all means, enlighten me! :P

TIA. WR!


Solution

  • You don't have the syntax in your output loop quite right, it's basically the same as the assignment loop. And you do need to use the same name as the loop variable (j, not k):

    $dbq = '';
    for ($j=1;$j<3;$j++) {    
      $dbq .= "stuff ${"var$j"} ";
    }
    echo $dbq;
    

    Output:

    stuff foo stuff foo
    

    Demo on 3v4l.org

    Ultimately though the best solution for this is an array:

    for ($k=1;$k<3;$k++) {
      $var[$k] = 'foo';
    } // so far so good
    
    $dbq = '';
    for ($j=1;$j<3;$j++) {    
      $dbq .= "stuff {$var[$j]} ";
    }
    echo $dbq;