0

I'm new to PHP so please forgive me if this is a stupid question.

How do you include a variable in a variable?

What I mean is:

<?php

   $variable_a = 'Adam';
   $variable_b = '$variable_a';

?>

In other words the second variable is the same as the first one.

I won't bother explaining why I need to do it (it will confuse you!), but I just want to know firstly if it's possible, and secondly how to do it, because I know that code there doesn't work.

Cheers,

Adam.

Adam McArthur
  • 950
  • 1
  • 13
  • 27

4 Answers4

4

Don't use the quotes, they indicate a string. Just point to the variable directly, like this:

$variable_b = $variable_a;
Oldskool
  • 34,211
  • 7
  • 53
  • 66
2

If you want the variables to be equal, use:

$variable_b = $variable_a;

If you want the second variable to contain the first, use variable parsing:

$variable_b = "my other variable is: $variable_a";

Or concatenation:

$variable_b = 'my other variable is: ' . $variable_a;
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
2

PHP have this advantage in producing one string variable's value based on another. To do this, write code like this:

$b = "My name is $name.";

The following code does NOT work:

$b = '$name';

Other occasions in which coding like this works are:

$b = <<<STRING
    Hello, my name is $name...
STRING;

If you want to access an array, use:

$b = "My ID is {$id['John Smith']}.";

and of course,

$b = <<<STRING
    Hello, my name is {$username}, my ID is {$id['John Smith']}.
STRING;

I recommend using {} because I frequently use Chinese charset in which occasion coding like

$b = "我是$age了。";

will cause PHP look up for variable $age了。 and cause error.

1

Either without quotes to reference the variable directly, since quotations means it's a string

$variable_b = $variable_a;

Or you can ommit the variable in double quotations, if you want it to appear in a string.

$variable_b = "My name is $variable_a";
Stefan Konno
  • 1,337
  • 2
  • 16
  • 28