Posted By

dialeleven on 08/04/12


Tagged

php variable names


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

CFJRB


Variable in PHP variable names


 / Published in: PHP
 

URL: http://www.justskins.com/forums/variable-in-variable-name-96140.html

Create variable named PHP variables. Having dynamically named variables can be helpful when dealing with loops and arrays. For example instead of having seven if () statements for handling seven individual days of the week, you could reduce it to one if statement by doing a loop with seven iterations and dynamically create your variable names.

  1. // create fifty (50) variable named variables named my_var1, my_var2...
  2. $name = "my_var";
  3.  
  4. for ($i = 0; $i < 50; $i++)
  5. {
  6.  
  7. ${$name.$i} = rand();
  8.  
  9. }
  10.  
  11. echo $my_var3;
  12.  
  13.  
  14. // slightly more complex example to create a variably named array w/concatenation
  15. $name = "my_var";
  16.  
  17. for ($i = 1; $i <=5; ++$i)
  18. ${$name . $i . '_arr'} = rand();
  19.  
  20. echo $my_var2_arr;

Report this snippet  

You need to login to post a comment.