Browsing articles tagged with " variables"
Jun 2, 2010

variable variables in php and javascript

intro
ok, so the title of this one is a little weird but it is a very common thing that i run into, and i find myself looking this up each time and realized i should just add it to the blog. first off, what is a variable variable. basically its a variable whose name is assigned via a variable. so lets say you have a variable ($txt, or var txt) that you assign a value of “myVar” to. echo/alerting the txt variable will display myVar to the screen. well what if you want to use that word as the name of a variable and assign it a value of “test”. you could simply use $myVar = "test"; or var myVar = "test"; right? simple! but, if youve received a variable (say from some other method/function) containing a word, and you want to use that word as a new variable name. you need a way to declare the variable with the name stored inside the received variable. luckily both php and javascriptp have a way to do this.

php
in php you just use two dollar signs ($). so if you have a variable $a and inside of $a is a string “myVar,” then $$a = "hello"; would be the same thing as using $myVar = "hello";. to reference it later, echo $a; would print “myVar” to the screen and echo ${$a}; or echo $myVar; would print “hello” to the screen.

javascript
in javascript its a little more difficult but certainly possible. lets use the exact same scenario but switch to javascript syntax. to assign the string inside var a to a var myVar you would use window[a] = "hello"; referencing it later, alert(a); would yield an alert box containing “myVar” and alert(myVar); or alert(window[a]); would yield an alert box with “hello” inside.

conclusion
you may not have ever been faced with a situation where youve needed to do this, but for those of you who have and couldnt find the results, youre welcome! im faced with this right now, and knowing i can do this is certainly making my life much easier