1

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...:-)

1
  • Remove the backslash before the dollar sign? Commented Oct 18, 2016 at 3:10

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

omg!! First variable functions, now variable variables. Thank you for the info. I didn't know this existed...:-)
@user3889963 I made a mistake in my original answer, don't know if you tried it yet, but I just edited it to fix it, should work properly now.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.