What are the best practices for handling the id attribute within nested elements like <span> within <h2> tags in PHP?

When handling the id attribute within nested elements like <span> within <h2> tags in PHP, it is important to ensure that each id attribute is unique on the page to comply with HTML standards. One way to achieve this is by dynamically generating unique ids using a counter variable or a unique identifier for each element.

&lt;?php
$counter = 1;

// Loop through elements and assign unique ids
foreach ($elements as $element) {
    $unique_id = &#039;element_&#039; . $counter++;
    echo &#039;&lt;h2 id=&quot;&#039; . $unique_id . &#039;&quot;&gt;&lt;span id=&quot;&#039; . $unique_id . &#039;_span&quot;&gt;Nested Element&lt;/span&gt;&lt;/h2&gt;&#039;;
}
?&gt;