Variable in PHP variable names


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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;

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.