Jump to content

Capturing Output Of A For Loop In A Variable


bukwus
 Share

Recommended Posts

HiI've built a form so that the questions generate automatically. I set the number of questions into $numQuestions, I put the questions in an array called $questions, then used a typical for loop to create the questions in an HTML table.

for ($i = 1; $i <= $numQuestions; $i++) {			echo '<tr>			<td align="left" valign="top" border="0">					<p>'.$questions[$i].'</p>					<textarea rows="5" cols="53" id="data'.$i.'" name="data'.$i.'">'.$_POST['data'.$i].'</textarea>				</td>			</tr>';		}

It works fine. The purpose of this is because I'm building many forms with similar structure, but different questions and this saves a great deal of time.Here's where I'm getting stumped:When a user fills out the form and submits it, the results are sent to us as well as to their email address. I need to create a similar for loop that can generate the questions and the user's answers in the form email that is sent. The body of the email is the value of the $email_body variable.So, is there a way to assign the output of a for loop to the value of a variable?Many thanks,Andy

Link to comment
Share on other sites

Instead of using echo to print the information, just append it to your email body variable.
I'm probably misunderstanding you, but do you mean something like this? I tested it and it just returns the literal value of $email_body. Am I just doing it wrong?
for ($i = 1; $i <= $numQuestions; $i++) {			$email_body = '.$question['.$i.']."\n"			.$_POST[\'data\''.$i.']."\n"';		}

Link to comment
Share on other sites

That's going to overwrite $email_body every time through the loop, instead of add to it. But yeah, in that code you're building a string of PHP code. You're probably looking for something more like this:

$email_body .= $question[$i] . "\n" . $_POST['data' . $i] . "\n";

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...