Foreach Loop Nesting Does Not Work

advertisements

So I'm working on a form, and I'm using PHP to pull an array of contacts out of a database. As the result is an array, I'm using a foreach loop to echo the contacts and move on. Here is my code:

    <p class='contact-list'>
      <?php

        foreach( $contacts as $contact ){
            echo "<p><input type='radio' name='contact' id='contact-{$contact['id']}' value='{$contact['id']}'/>";
            echo " {$contact['name']}</p>";
        }

      ?>
    </p>

I'm doing this because I want each of the contacts to be placed as a child to the .contact-list, and when the page renders, the source seems like it should be:

<p class='contact-list'>
    <p><input type='radio' ...
    </p>
    <p><input type='radio' ...
    </p>
</p>

That's not how it is. Instead of being children to the .contact-list, each contact is a sibling to it, and I'm wondering why this is happening.

The source from the page after it's rendered is this:

<p class='contact-list'></p>
<p><input type='radio' name=''...
</p>
<p><input type='radio' name=''...
</p>

Can anyone explain why the Paragraph tag is closing before the foreach loop runs?

Update:

I decided to use a div instead of a paragraph, and then nesting worked right, so I'm assuming that this is a trait of the paragraph tag. That said, I'm still interested in finding out why the paragraph tag does this.


Because p is a block element which can contain only inline elements. But you put other p-elements in it. Use span instead the ps and this should work as you expect