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"...
$varName = 'Q'.$i;
$a .= $$varName;
Or just
echo $$varName . "<br>
";
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;
To create the variable variable, use:
$a = ${'Q'.$i};
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 )
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;
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};
}
?>
$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;
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];