How to properly add multiple form elements in a loop? I have a form where I need to loop through an array and display multiple form elements in a specific area.

Example:

$form_layout = 'Some html';
$form_layout .= '&lt;div&gt;';

foreach($something as $key =&gt; $value) {
    $form_layout .= 'some html';
    $form_layout .= 'some html';

    // I need this to be displayed in between the above and below code
    // in the layout
    $form['awesome_element'] =&gt; array(
        '#type' =&gt; 'textfield',
        '#size' =&gt; 5,
        '#value' =&gt; 0
    );

    $form_layout .= 'some html';
    $form_layout .= 'some html';
}

$form_layout .= '&lt;/div&gt;';
$form_layout .= 'Some html';

$form['some-other-awesomeness'] = array(
    // ...
    '#prefix' =&gt; $form_layout,
);


Doing it like the example puts the textfields after all the other page elements. I have tried using #prefix and #suffix but that breaks the layout even worse.

Any ideas on what I should do?

Edit: For clarity...

If I had layout elements such as a div tag I need my form elements, such as textfields, to be inserted in between those div tags.

So I need it to output something like this:

&lt;div&gt;
FORM ELEMENT
FORM ELEMENT
FORM ELEMENT
&lt;/div&gt;


Instead it is outputting something like this:

&lt;div&gt;&lt;/div&gt;
FORM ELEMENT
FORM ELEMENT
FORM ELEMENT


Hopefully that is more clear, sorry if the above is confusing. Looking at code for the last 20 hours.

Edit2: added some visual stuff to make it easier to understand
Could you do something like the following:

$form['openingdiv'] = array(
  '#markup' =&gt; '&lt;div&gt;'
);

//Do all your foreach stuff here

$form['closingdiv'] = array(
  '#markup' =&gt; '&lt;/div&gt;'
);


(Sorry it's a bit simple..I'm tired :-p)