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 ?

1
  • 1
    Any time you find yourself creating variables like that, you should almost always be using an array instead of separate variables. Commented Sep 24, 2020 at 23:23

1 Answer 1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.