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.

4
  • Better to write without quotes, but if you want to use quotes then use double quotes instead of single. Commented Feb 1, 2012 at 10:17
  • stackoverflow.com/questions/3446216/… Commented Feb 1, 2012 at 10:18
  • dont forget: PHP variables Commented Feb 1, 2012 at 10:20
  • Read the reference variable and the variables in single in double quotes. it will remove your confusion. Commented Feb 1, 2012 at 10:24

4 Answers 4

4

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

$variable_b = $variable_a;
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh! So you don't include the quotes. No wonder it was outputting as text. Thanks mate perfect!
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;

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.