LB79
LB79

Reputation: 1285

Dynamic Variable Name / Increment Variable Name

Please can someone assist me with dynamic variables within a loop? In the code below, I have 4 variables and an echo that loops 4 times.

When the loop runs, each variable should echo (in the code I've inserted $var* as a place holder).

How is it possible to increment $var* within the echo statement ($var1 should echo, then $var2 and so on)?

Many thanks

$var1 = 'A';
$var2 = 'B';
$var3 = 'C';
$var4 = 'D';

for ($i = 1; $i < 5; $i++) {

    echo ($var*);

}

Upvotes: 0

Views: 1009

Answers (1)

Casper
Casper

Reputation: 81

This is what is called a "variable variable." A variable definition is comprised of two parts: the dollar sign, which tells the interpreter that it's a variable, and the variable name per se, which in short is a string; I'll call it "body" here.

So, if you have $var = 'my_other_var' and $my_other_var = 'hey', you can use the string "my_other_var" as the "body" of a the variable call.

Then echo $$var yields "hey".

Here with your example:

<?php

$var1 = 'A';
$var2 = 'B';
$var3 = 'C';
$var4 = 'D';

for ($i = 1; $i < 5; $i++) {

    $varToEcho = "var$i"; // will become var1, var2, var3 and so on

    echo $$varToEcho;

}

Upvotes: 1

Related Questions