PHP: Convert string to variable?!

  • Post category:PHP
  • Post comments:0 Comments
PHP: Convert string to variable?!
PHP: Convert string to variable?!

Problem:

$button0 = "candy";
$button1 = "pop";
$button2 = "nuts";
$button3 = "sugar";

$buttons = 4;
$counter = 0;
while ($counter < $buttons) {
$printbutton = "$"."button".$counter;
echo($printbutton."<br>"); // echos $button0 but not the value of $button0
$counter = $counter+1;
}

What happens is that $printbutton always prints $buttonx (where x = $count) but I want it to print candy or nuts or whatever $buttonx’s value is.

Solution:

$printbutton = ${‘button’ . $counter};

For more information:
http://us2.php.net/language.variables.variable