Question

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.

Was it helpful?

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.

OTHER TIPS

Generally if $val holds the name of the variable you want to reference, $$val will give you the value of that variable. In your case, since you are also indexing into an array, it is slightly more complicated to write.

You need to change

$val = $i."_cat[".$row."]"; // HERE'S WHERE I'M HAVING DIFFICULTY
$cat = $cat.$val.",";

to

$val = $i."_cat";
$cat = $cat.${$val}[$row].",";

Refer to the PHP documentation section on variable variables for all the details.

Also, variable names cannot start with numbers, so you will need to tweak the naming scheme a bit.

Update: Fixed the code (indexing into an array is slightly more complex to write), added variable name note.

See it in action.

I'm guessing your field names in the HTML Page are actually called stuff like <select name="1_cat[0]"> and the like?

You'd access those, using your loops, like this:

$_POST[$i . '_' . 'cat'][0] ... or .... $_POST["{$i}_cat"][0]
$_POST[$i . '_' . 'cat'][1] ... or .... $_POST["{$i}_cat"][1]
$_POST[$i . '_' . 'cat'][2] ... or .... $_POST["{$i}_cat"][2]
etc...

Unless you've got register_globals turned on (you don't, right? please tell me you don't...), there will NEVER bee a PHP variable named $1_cat[0] to begin with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top