Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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