0

im confuse that...

like example:

$Q1 = "hello";
$Q2 = "world";
$Q3 = "StackOverflow";

$i = 1;

while($i < 3) {
  $a = "$Q".$i; //I think this is wrong.    
  echo $a; // i tried ${$a} doesn't work =/

  $i++;
}

then output format:

$Q1
$Q2
$Q3

but there is not output like this: hello world StackOverflow

I want like $Q + $i become $Q1 to answer is: "hello"...

1
  • These are called variable variables or variables with variable names. Jun 17, 2011 at 20:37

7 Answers 7

9
$varName = 'Q'.$i;
$a .= $$varName; 

Or just

echo $$varName . "<br>\n";
0
3

To create the variable variable, use:

$a = ${'Q'.$i};
1

echo $Q1 . $Q2 . $Q3; will output what you're looking for.

Alternatively, you could do this:

$a = '';

for($i = 1; $i <= 3; $i++)
  $a .= ${'Q' . $i};

echo $a;
1

What you are doing there is simply printing the string '$Q1', '$Q2' and '$Q3'. In PHP you use dynamic variable names this way:

<?php
$Q1 = 'hello';
$Q2 = 'world';
$Q3 = 'StackOverflow';
for ($i = 1; $i <= 3; $i++) {
    echo ${'Q' . $i};
}
?>
1

PHP does support variable variable names, denoted using $$. This will do what you want.

$qvar = 'Q'.$i;
$a = $$qvar;

However, this is considered very poor practice -- almost as bad as using eval() (and for similar reasons).

The correct answer would be to create an array of $Q, and referencing array elements;

$Q = array(
        "hello",
        "world",
        "StackOverflow")

$a = $Q[0] . $Q[1] . $Q[2];
0

Yeah. When you have double quoted strings, and you put a dollar sign and something else in it, it interprets it as a variable. (it also escape things like \n)

Example

$test = "hi";
echo "$test world"; //This outputs hi world

In your case, $Q doesn't exist. The default PHP behaviour is to ignore that error and just puts out nothing. This is why it's recommended to report all problems with your code. Check out http://php.net/manual/en/function.error-reporting.php for details.

Solution to your problem would be using single quoted strings. do $a = '$Q'.$i;

0
$Q = array("hello", "world", "StackOverflow");
foreach($Q as $w) {
    echo $w;
}

If you can't do something like this then you will need to use dynamic variables:

$var = 'Q' . $i;
echo $var; 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.