Category:php

how-to-turn-variable-value-into-variable-name

Variable Variables in PHP

i-1

Every so often when you are writing a php file, we all run into a situation where we would like for the name of the

string that is inside of your php variable to be converted into the actual name of another variable.

After a fair amount of hunting around the internet and getting sent off into PHP code hunting limbo for a few hours, I suddenly remembered that this was something that I had  found a solution to some time ago. Now, had I been prudent about my little discovery, I would have put it up here on mrarrowhead.com. Instead I forgot about it until I accidentally ran across variable variables agains in the php manual. Variable variables was exactly what I was looking for to get a string from one variable and change it to the name of another variable in my php scipt.

So here goes:

 

^php

$var = \"varIwannaMake\";

$$var = \"Im in varIwannaMake\";

echo $$var.\" //<--- this will output the above sentence\";

echo $varIwannaMake; // this will output the same thing

 

?*

 

The scirpt above will output the following:

Im in varIwannaMake

Im in varIwannaMake

 

Short and sweet  - simple to use -- hope you like.

 

 

 

Author: D.Shaun Morgan