1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Building Variables In PHP

How can I build a variable from other variables?


A question I often get is this: how can I make multiple variables into one? The problem is, you put them together, you go to call the variable, but instead of acting like a variable it acts like text. Here is one of the examples sent to me.
 $test = "success";
 $open = "$";
 $close = ";";
 $primary = "test";
 $ID = "$open$primary$close";
 echo $ID;

What the user wants is for the echo of $ID to be "success", but instead it is echoing "$test". What you need to do to make this work, is really very simple. Just put it in between {} symbols. For example:
 $test = "success";
 $primary = "test";
 $ID = ${$primary}; 
 echo $ID; 
Now when we execute the code, it is setting $ID equal to $test and therefor the output will be "success".
  1. About.com
  2. Technology
  3. PHP / MySQL
  4. Advanced PHP
  5. How to Build Variables on the Fly in PHP

©2014 About.com. All rights reserved.