Adam McArthur
Adam McArthur

Reputation: 980

PHP Variable used in a variable

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.

Upvotes: 0

Views: 114

Answers (4)

Lucifer Orichalcum
Lucifer Orichalcum

Reputation: 231

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.

Upvotes: 2

Stefan Konno
Stefan Konno

Reputation: 1337

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";

Upvotes: 1

cmbuckley
cmbuckley

Reputation: 42547

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;

Upvotes: 2

Oldskool
Oldskool

Reputation: 34877

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

$variable_b = $variable_a;

Upvotes: 4

Related Questions