0

What is trying to do is call existing data inside loop, saving them as new varable $m then print $m value.

$a_1 = "A";
$a_2 = "B";
$a_3 = "C";

for ($x = 1; $x <= 3; $x++) {
    
$m= $a_.$x;
echo $m;

}

expected print was "ABC";

But $a_.$x not registering as variable inside loop, eighter storing value "A" for loop $a_1 which i expected.

How to do that ?

Zils
  • 403
  • 2
  • 4
  • 19
  • 1
    Any time you find yourself creating variables like that, you should almost always be using an array instead of separate variables. – Barmar Sep 24 '20 at 23:23

1 Answers1

1

You can do this using variable variables:

$a_1 = "A";
$a_2 = "B";
$a_3 = "C";

for ($x = 1; $x <= 3; $x++) {
    $variableName = 'a_' . $x;
    echo $$variableName;
}

I'm not sure what the intention is behind this, but it would in general be a better idea to store these values in an array as such:

$a = [
    1 => 'A',
    2 => 'B',
    3 => 'C'
];

for ($x = 1; $x <= 3; $x++) {
    echo $a[$x];
}