简体   繁体   中英

Foreach Loop Nesting Isn't Working

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 p s and this should work as you expect

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>";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM