Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Displaying All Items

There is a cleaner way to generate the html in PHP?

just wondering if there is a cleaner way to conectinate this:

<?php
foreach($catalog as $item) {
                echo "<li><a href='#'><img src='" 
                    . $item["img"] . "' alt='" 
                    . $item["title"] . "' />" 
                    . "<p>View Details</p>"
                    . "</a></li>";
            }

thanks!

2 Answers

Vince Brown
Vince Brown
16,249 Points

Hey Noob, you can just close the foreach drop your html in the middle, then reopen and echo out values as needed

<?php foreach ( $catalog as $item ) : ?>
    <li>
        <a href='#'>
            <img src="<?php echo $item['img']; ?>" alt="<?php echo $item['title']; ?>" />
            <p>View Details</p>
        </a>
    </li>
<?php endforeach; ?>

when i try to do the following the books are not displaying like they need to be, another 3 books are added below them:

https://gyazo.com/493269ccf62127cf7072bc5f3b11ff0d

and the original: https://gyazo.com/204332711d608e35aa26ac86f465630a

there are 3 books in each row and in the previous code each row contain 4