Jump to content

Capturing the output of a for loop in a variable


bukwus

Recommended Posts

Hi

I'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

for ($i = 1; $i <= $numQuestions; $i++) {
		$output .= '<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>';
	}
echo $output;

 

now you have the output in the variable and echo'd it as well to the browser

Link to comment
Share on other sites

for ($i = 1; $i <= $numQuestions; $i++) {
		$output .= '<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>';
	}
echo $output;

 

now you have the output in the variable and echo'd it as well to the browser

 

Thank you. Worked like a charm.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.