How can a counting variable be used to properly close div elements within a loop in PHP?

When using a loop to generate multiple div elements in PHP, it's important to properly close each div element to maintain the structure of the HTML document. One way to achieve this is by using a counting variable within the loop to keep track of the number of div elements generated and close each div element accordingly.

// Initialize the counting variable
$count = 0;

// Loop to generate div elements
for ($i = 0; $i < 5; $i++) {
    echo "<div>";
    // Content of the div element
    echo "</div>";
    
    // Increment the counting variable
    $count++;
    
    // Close the div element if it's the last one
    if ($count == 5) {
        echo "</div>";
    }
}