1

I'm a bit confused about variable variables.

What I like to do is print the value of $var1, $var2 and $var3:

$var1 = 'a';
$var2 = 'b';
$var3 = 'c';

$i = 1;

while ( $i <=3 ) {
    echo $var.$i;
    $i++;
}

I know $var.$i; is not correct, but I think it shows what I would like to achieve; the while-loop should change it to $var1, $var2 and $var3;

I've tried the following:

$var1 = 'a';
$var2 = 'b';
$var3 = 'c';

$i = 1;

while ( $i <=3 ) {

    $current_var = 'var'.$i;
    $current_var = $$current_var;

    echo $current_var;

    $i++;
}

But that doesn't work. I think because $var1, $var2 and $var3 are recreated in the while-loop instead of using the actual value. Not sure if that's correct, but that the only thing I can think of.

3
  • what should be the desired output?? Commented Apr 4, 2013 at 4:05
  • You could try $($var.$i). Commented Apr 4, 2013 at 4:07
  • I ran the above code and output was abc Commented Apr 4, 2013 at 4:07

3 Answers 3

4

Try this instead:

echo ${"var".$i};

Curly braces can resolve to variable names without having to use the dollar-dollar approach.

See: Variable Variables in PHP

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

Comments

2

Try this one.

<?php
$var1 = 'a';
$var2 = 'b';
$var3 = 'c';

$i = 1;
while ( $i <=3 ) {

    echo ${'var'.$i};

    $i++;
}
?>

Comments

0

Are you trying to do something like this. Then use array

$my_data = array();
$my_data[1] = 'a';
$my_data[2] = 'b';
$my_data[3] = 'c';

// Method 1
$i = 1;
while ($i <= 3) {
  echo $my_data[$i];
  $i++;
}

// Method 2
foreach ($my_data as $data) {
  echo $data;
}

// Output

abc

abc

Comments

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.