PHP - Adding divs to a foreach loop every 4 times

PHP - Adding divs to a foreach loop every 4 times

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP - Adding divs to a foreach loop every 4 times

Handling grouped output within a simple foreach loop is a common pattern, but it often trips up developers who are used to iterating linearly. The core challenge isn't just printing data; it's managing state across iterations without cluttering the logic with nested conditionals or complex counters. When you need to wrap every fourth item in a container like <div>, the solution relies on understanding the modulo operator and how to cleanly close tags when appropriate.

The most straightforward approach involves using the modulo operator (%) inside your loop to detect specific indices. If you iterate through $users_kicks, you can calculate the current position by checking ($i % 4 === 0) or, more elegantly in modern PHP, by leveraging the index directly if available via destructuring. However, since the provided snippet uses a simple key-value iteration without an explicit counter variable, we must introduce one to track progress accurately.

Here is a practical implementation using a counter initialized before the loop starts:

$count = 0;

foreach ($users_kicks as $kicks) {
    echo '<div>' . PHP_EOL; // Open div for every 4th item start? No, that's wrong logic.
    
    // Actually, we need to open a div every 4 items and close it after the 4th.
    // A cleaner way is to check if (index + 1) % 4 == 0 to close, 
    // but opening on index % 4 == 3 is also valid.
}

Wait, let's refine that logic. The goal is to group four items together. If we start a <div> every time we encounter an item where (index + 1) % 4 === 0, we are essentially closing groups as they complete. But we need to open them at the start of the group.

The most robust pattern is to check if the current index (starting from 0) modulo 4 equals 3. This means:

  • Index 0, 1, 2: No wrapper yet.
  • Index 3: Start a new wrapper? No, that's messy because we'd have unclosed divs if the total count isn't divisible by 4.

A better strategy is to open a <div> when (index + 1) % 4 === 0 and close it immediately after printing the fourth item, but only if we track groups explicitly. Actually, the cleanest way to handle "wrap every 4" without worrying about trailing unclosed tags (unless you want them closed by HTML standards implicitly or via a final check) is to open the div at the start of every new group and close it after the fourth item.

Let's stick to the simplest logic: Open a <div> when we are starting a new group, and close it when we finish one.

$index = 0;
foreach ($users_kicks as $kicks) {
    // Check if this is the first item of a new group (1-based index divisible by 4? No.)
    // Let's use 0-based index.
    // If $index % 4 == 0, it's the start of a group (0, 4, 8...).
    // If ($index + 1) % 4 == 0, it's the end of a group (3, 7, 11...).
    
    if ($index % 4 === 0) {
        echo '<div>' . PHP_EOL;
    }

    echo htmlspecialchars($kicks->brand) . PHP_EOL;

    if (($index + 1) % 4 === 0) {
        echo '</div>';
    }
    
    $index++;
}

This logic handles the grouping dynamically. If $users_kicks has exactly 12 items, you get three clean <div> blocks. If there are 13 items, the last item will sit outside any div, which is often the desired behavior for partial groups. You might choose to wrap the remainder in a final <div> or leave it raw depending on your HTML structure requirements.

One common pitfall here is relying solely on echo statements inside the loop when dealing with large datasets. While PHP can handle thousands of iterations, string concatenation with multiple echo calls prevents output buffering optimization in some contexts. For performance-critical loops, collecting chunks into an array and joining them with implode() or constructing a single string buffer is significantly faster. However, for small lists like user kicks, the readability of direct echoing usually outweighs the micro-optimization concerns.

Another consideration is HTML escaping. The source material simply echoes $kicks->brand, which is dangerous if user input is involved. Always use htmlspecialchars() to prevent XSS vulnerabilities when outputting data into HTML contexts. This ensures that special characters like quotes or ampersands are rendered safely as text rather than interpreted as code.

If you are working within a Laravel application, you might consider using the blade template engine or a helper method to handle this grouping logic outside the loop entirely. For instance, you could create a closure that returns HTML segments and map over the data in chunks using array_chunk(). The array_chunk() function splits an array into smaller arrays of a given size, making it trivial to iterate over each chunk and wrap its contents in a single <div>.

$chunks = array_chunk($users_kicks, 4);

foreach ($chunks as $chunk) {
    echo '<div>' . PHP_EOL;
    foreach ($chunk as $kicks) {
        echo htmlspecialchars($kicks->brand) . PHP_EOL;
    }
    echo '</div>' . PHP_EOL;
}

This approach separates the grouping logic from the rendering logic, making the code easier to read and maintain. It also guarantees that even if the total number of items isn't a perfect multiple of four, the last chunk (containing fewer than 4 items) is still wrapped correctly. This separation of concerns is a hallmark of clean code architecture.

Our network