0

I want to know how can I get a variable which the combination of a character string and another variable.

Example:

$var1 ch1 and i want the name of the final variable like below $ch1var1

id; echo $nbr$id; ?>

Thank you.

  • Take a look at the PHP manual for some quick examples. http://php.net/manual/en/function.echo.php – DACrosby Mar 12 '13 at 23:43
  • Potential duplicate. See here: http://stackoverflow.com/questions/15230957/php-variable-from-variable – Derek W Mar 12 '13 at 23:44

2 Answers2

5
    $var1 = "Hello";
    $nbr = "var";
    $id = 1;
    echo ${$nbr.$id};

DEMO VIEW

Use var concatenation

Sam
  • 2,950
  • 1
  • 18
  • 26
  • 2
    is ${} syntax new? never seen it before. – j_mcnally Mar 12 '13 at 23:35
  • 1
    It is a way to use variable variables. Makes the code more readable. Here is a nice link with more discussion about the practice: http://php.net/manual/en/language.variables.variable.php – Derek W Mar 12 '13 at 23:36
  • yeah i know but has it always been around? – j_mcnally Mar 12 '13 at 23:37
  • 1
    It's certainly been around throughout the life of PHP5, don't recall if it existed in PHP4 – Mark Baker Mar 12 '13 at 23:40
  • 1
    The syntax existed at least as early as PHP4.2 - http://techdoc.kvindesland.no/devcenter/php4.2/language.variables.variable.html – Mark Baker Mar 12 '13 at 23:48
  • @MarkBaker: I seem to recall this syntax being used in a PHP4 environment, too: it's always been the way to avoid ambiguous statements like `echo "$some['array']";` or `echo "{$some['array']}";`, same goes for object methods, and properties of course – Elias Van Ootegem Mar 12 '13 at 23:49
  • Back as far as PHP3 - http://techdoc.kvindesland.no/devcenter/php3/variables.html - can only find $$a format in PHP2 – Mark Baker Mar 12 '13 at 23:50
0
echo ${$some . $combination . $of . $variables . "or" . "strings"};
moonwave99
  • 21,957
  • 3
  • 43
  • 64