Variable Variables

by Kevin Partner on 22nd November, 2007

Here’s the problem. You have ten similar fields in a form called “field1″ to “field10″. You want to pull out the text value for each field and create a shorter variable for each. You’d want to do this in a loop because we all hate repetition don’t we? What you need is what PHP calls “variable variables”: other languages use the “eval” construct and similar.

for($n=1;$n<11;$n++)
{
$thisfield="field".$n; //this sets the $thisfield variable to "field1" up to "field10" in order
$$thisfield=$_POST[$thisfield]; //this adds the next variable in the POST superglobal
}

What the extra $ in $$thisfield means is “the contents of the variable whose name is contained in $thisfield”. In this case, when the loop is run the first time, it will create a new variable called $field1 and pass into it the value of the $_POST['field1'].  So, in this case, we end up with ten new variables ($field1 – $field10) without having to create them by hand.

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Add to favorites

Leave a Comment

Previous post:

Next post: