View Full Version : Using a variable's value to declare/name another variable

01-10-2010, 08:16 PM
I would like to use a variable's value to create/declare another variable in PHP. I saw this answer in the Javascript forum, and I was wondering if you can do this in PHP? Somewhere, I remember seeing where you can use a global this[$var + "name"] to create a variable name in Javascript. Can you use "this[]" in PHP? Thanks.

Here's the Javascript answer:

Say the variable menu contains the value "menu1" and I want to declare a variable called menu1_status. I want to do something like:

var eval(menu + "_status") = 1;

Except that doesn't work, even without the var part (with var it complains about syntax). Hopefully you understand what I'm trying to accomplish! Any suggestions are appreciated. Thanks in advance.

Accepted answer:
window[menu+ '_status']=1;

01-10-2010, 08:30 PM
You can't use this in PHP unless you're in an object context. $this is reserved for scoping inside of methods to identify class level variables or methods. PHP does not mask scope, and it is required in that context.
To answer you're question, this is far easier in PHP than most languages:

$a = 'hello';
$$a = 'world';

print $a . ${$a}; // Prints helloworld
// OR
print $a . $hello; // Prints helloworld

For the most part, you never need to use variable variables since the data interpreted by the variable $hello, can be accessed without ever knowing the value of $a. See this section on variable variables (http://php.ca/manual/en/language.variables.variable.php).

01-10-2010, 09:23 PM
Thanks for the tip. I'm trying to set a variable equal to a variable, and it doesn't want to cooperate. I'm running a "For" loop to cycle through the alphabet, and I'd like to name each variable based on the letter.

e.g. I would like $b to equal "b" and so on.

$temp=(string) strtolower(chr($i));
// $$temp=$temp; does not work...
$temp2=(string) strtolower(chr($i));
$$temp = $temp2; // not working either

echo "\$b: " . $b . "<br>"; // outputs $b: (NO VALUE?)

Thanks for any suggestions.

01-11-2010, 05:58 AM
Lets see, as soon as you hit $i, it will set $i as 'i'. Since it will try to interpret it as a number, it will fail, and loop infinitely at that point. Yeah that looks about right.
Anyway, I'd just use an array, which you can fill with a range:

$aLetters = range('a', 'z');

Note that you cannot specify 'A', 'z', as you'll get unexpected results. At this point, you can use an array_combine($aLetters, $aLetters) if you wanted, and extract them to global scope, which will create $a = 'a', $b = 'b', etc. I don't really think thats necessary though.