tags:

views:

50

answers:

2

I have a form with a lot of textareas.

<textarea cols="30" rows="6" id="q1"></textarea>
<textarea cols="30" rows="6" id="q2"></textarea>
<textarea cols="30" rows="6" id="q3"></textarea>
...
<textarea cols="30" rows="6" id="q54"></textarea>

Don't ask why we need 54 questions.

I want to print them out but don't want to do it manually.

$i = 1;
while ($i <= $countTextareas) {
  $questID = "q" . $i;

  $question = $_POST[$questID];

  echo "Question " . $i . ": " . $question . "<br />";

  $i++;
}

The result of that code is:

Question 1: <br />

Any assistance or even a point in the general direction would be great.

Thanks in advance.

It may not be the most elegant solution but it works...

$i = 1;
while ($i <= $countTextareas) {
    $question = $_POST['question'][$i];
    echo "Question " . $i . ": " . $question . "<br />";
    $i++;
}
+1  A: 

Since you are using PHP, you should exploit PHP's nifty feature of turning a name attribute like question[] into an array.

So if you had...

<textarea name="question[]" rows="5" cols="5">
</textarea>

<textarea name="question[]" rows="5" cols="5">
</textarea>

Your $_POST would be...

question[0] = 'whatever';
question[1] = 'something else';
alex
its not really an PHP Feauture is it? I mean the POST Request is someting[1] = "something", something[2] = "someting else" that PHP then receives that as an array just seams logical
Hannes
Well logical, but it does make the array automatically.
alex
Would that also work with an id instead of name?
StefWill
No. An id can't contain the characters `[` or `]` and is never submitted to the server.
David Dorward
I don't get how you would iterate through the question array to echo them. $question = $_POST['question']; $i = 1; while ($i <= 54) { echo "Question " . $i . ": " . $question[$i] . "<br />"; $i++;}
StefWill
@SteWill You don't need to build the key if you do it this way - you don't even need to know the limit (though it'd be nice to `array_slice()` it for security). You just iterate through the name `question` and subscript each member. Once you figure it out, it is very handy :)
alex
+2  A: 

How about good old foreach?

foreach ($_POST as $key => $value) {
    echo 'Question '.$key.': '.$value.'<br />';
}
elusive