What are some best practices for handling grouping of results in PHP loops to avoid premature closing of elements?

When grouping results in PHP loops, it's important to ensure that elements are not prematurely closed before all related items have been processed. One way to handle this is by using a flag variable to keep track of when a group starts and ends, allowing you to properly close elements only when needed.

$groupStarted = false;

foreach ($results as $result) {
    if ($result->group != $currentGroup) {
        if ($groupStarted) {
            echo '</div>'; // Close previous group
            $groupStarted = false;
        }
        
        echo '<div class="group">';
        $currentGroup = $result->group;
        $groupStarted = true;
    }
    
    // Process individual result within the group
    echo '<div class="item">' . $result->name . '</div>';
}

if ($groupStarted) {
    echo '</div>'; // Close the last group
}