1

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.

Goldentoa11
  • 1,700
  • 2
  • 17
  • 29

2 Answers2

3

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

Sindhara
  • 1,423
  • 13
  • 20
  • 1
    +1. Another alternative is to make the contact-list a div element. – Jeff Lambert May 14 '12 at 14:09
  • @kuh-chan: Why can't the Paragraph tag take other block level elements? I would've thought that since both div and p were block-level, they both would work. – Goldentoa11 May 14 '12 at 14:16
  • @Goldentoa11: because the `p` is explicit defined for texts - and texts only contain inline elements. That's what I guess. – Sindhara May 14 '12 at 14:23
0

Have you tried this?

foreach( $contacts as $contact ){
        echo "<span><input type='radio' name='contact' id='contact-{$contact['id']}' value='{$contact['id']}'/>{$contact['name']} </span>";
    }
Tahir
  • 3,344
  • 14
  • 51
  • 69