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

nicholas maddren
nicholas maddren
12,793 Points

ID Question

If I use a php script to loop an item listing template I have does that mean that the template cannot use ID's as it will be displayed more than once?

Do all the html elements need to be class's instead of ID's?

2 Answers

Andrew Showalter
Andrew Showalter
14,028 Points

You could use ID's. What you could do is use some sort of variable that has an initial value of something like $1 = 1.

Then, you could use that on an ID element to make each unique by adding 1 to the counter each time it loops. For example:

<?php
$i = 0;
foreach($items as $item){
    $i = $i + 1;
    echo '<div class="someclass" id="someid-"' . $i . '">' . $item['title'] . '</div>'; 
};
?>

Basically, you are using an $i variable counter to increase by 1 each time the items loops through to make that individual item have a unique id.

Andrew Showalter
Andrew Showalter
14,028 Points

Edited slightly, but this should so about what you are trying to accomplish.

Cole Wilkes
Cole Wilkes
4,556 Points

I don't follow your question entirely. However, you can have multiple html elements with the same class. Any time the id attribute is used it must be unique to one html element.