user3889963 user3889963 - 1 month ago 7
PHP Question

access php variable through concatenation

I was trying to achieve something simple and was wondering if it was possible. Google search proved unhelpful this time. Probably it's not possible, but I am not sure. I have the following code:

<?php
//Enter your code here, enjoy!

$query1="yay";
$query2="it";
$query3="works";

for($x=1;$x<=3;$x++){
$query="\$query".$x; //I need to assign the above variables
echo $query;
}

?>


I want the output to be "yayitworks" but instead I get "$query1$query2$query3". Is there any way to get my result? I know a switch statement will help me achieve this, but am just curious.

Thanks in advance...:-)

Answer

What you want is variable variables: http://php.net/manual/en/language.variables.variable.php

$query = ${"query".$x}