Page 1 of 1

Capturing the output of a for loop in a variable

Posted: Wed Mar 10, 2010 2:30 pm
by bukwus
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


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.

Code: Select all

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


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Capturing the output of a for loop in a variable

Posted: Wed Mar 10, 2010 3:52 pm
by pickle
2 ways. You could change your for loop so that rather than echo()ing, it stores in a variable. You can then do what you want with that variable. Alternatively, you can put ob_start() before the for loop, and assign the buffer to a variable using ob_get_clean() after the loop.