Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Try this one.

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

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

    echo ${'var'.$i};

    $i++;
}
?>

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top