Search code examples
phpwebformsvariable-variables

Displaying Dynamic Variable Value


I have a form that will ultimately create a pipe delimited text file. The form contains multiple rows each row has multiple drop down fields named 1_cat[], 2_cat[], 3_cat[] etc.

In the form submission script I have:

if ($submit) {
   foreach($_POST['videofile'] as $row=>$item)
   {
      $videofile = $_POST['videofile'][$row];
      $videotype = $_POST['videotype'][$row];

      for($i=0; $i<=$drop_fields; $i=$i+1) {
         $val = $i."_cat[".$row."]"; // HERE'S WHERE I'M HAVING DIFFICULTY
         $cat = $cat.$val.",";
      }
      print "$videofile|$videotype|$cat";
      $cat = "";
   }
}

The code below outputs 1_cat[0],2_cat[0],3_cat[0], 1_cat[1],2_cat[1],3_cat[1] etc. -- so it displays the names, but not values of those variables as I would like it to do.

Any help would be greatly appreciated.


Solution

  • There are several things in this code snippet that should be corrected:

    A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. 1_cat is not a valid variable name. If you wish to use your form fields as variable names, you will need to change the field names in your form.

    videofile needs a $: $videofile

    The for loop counter can be incremented like this: $i++. This is cleaner and more standard than $i=$i+1.

    The line $cat = $cat.$val.","; uses $cat before it is initialized. You should provide an initial value for $cat before the start of the loop.