Modulus in a PHP loop

Modulus in a PHP loop

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

Stefan Bogdanescu

Founder & Senior Architect

Modulus in a PHP Loop: Getting the Indices Right

When you iterate through a list of items, the temptation is often to rely on the loop counter $i to determine when to execute specific logic. In your example, you are attempting to wrap every third item with a row-ending tag by checking if ($i % 3 == 2). This works because array indices in PHP start at 0. The sequence of indices is 0, 1, 2, 3, 4, 5, and so on.

The modulus operator % returns the remainder of division. When $i is 0, 1, or 2, dividing by 3 leaves a remainder of 0, 1, or 2 respectively. Once you hit index 3, 3 % 3 becomes 0 again. Therefore, checking for a remainder of 2 correctly identifies the last element of every group of three (indices 2, 5, 8...).

However, your specific question is how to detect when you are in the second iteration rather than the third within that group. You attempted $i % 2 == 1, but this logic fails because it checks for any odd number overall. Index 1 satisfies this condition (it is the second item in the first group), but index 3 also satisfies it (it is the first item of the next group, and 3 is an odd number). The modulus operator needs a divisor that aligns with your grouping size to be useful here.

To specifically target the second position within every triplet, you must check for a remainder of 1 when dividing by 3. The condition should be:

if ($i % 3 == 1) {
    // This runs for indices 1, 4, 7, etc.
}

This ensures that the logic only triggers when the index is one greater than a multiple of three. If you apply this to your snippet, you would move the closing </li> tag and the opening <li class="row"> tag inside the block where $i % 3 == 1 is true.

Adjusting the Logic Structure

In your current code, you have the opening row tag logic nested inside the item div, but the closing tag logic is separate. This creates a mismatch in how the HTML structure is built. If you want to close the group when you find the third item and open a new group immediately after finding the second item (or start a new group at the beginning), you need to be precise about where the boundaries lie.

Consider refactoring the loop slightly to handle the row initialization outside the conditional block or using the modulus to control the flow more cleanly. A common pattern in older PHP frameworks, which your snippet resembles given the base_url() helper and <div class="grid_8"> structure, often involves initializing the container before the loop and closing it inside the condition.

echo '<li class="row">'; // Start row once

for ($i = 0; $i < count($category_news); $i++) {
    echo '<div class="grid_8">';
    
    $classSnippet = '';
    if ($i % 3 == 1) {
        $classSnippet = ' candidate end'; // Adjusted condition for second item
    } elseif ($i % 3 == 2) {
        $classSnippet = ' candidate end'; // Logic for third item
    }

    echo '<div class="candidate' . $classSnippet . '">';
    
    // ... existing content ...
    
    echo '</div>';
    
    if ($i % 3 == 2) {
        echo '</li>';
    }
}

Why $i % 2 Doesn't Work Here

The core misunderstanding in trying $i % 2 == 1 stems from conflating "second item" with "odd number." While the second item of a group is indeed odd, the third item of the next group (index 3) is also odd. Modulus arithmetic requires the divisor to represent the cycle length. Since your grouping logic relies on sets of three, the divisor must be 3. Using a divisor of 2 ignores the fact that you are skipping items between groups.

If you need to handle this in a modern Laravel context, you might consider using array_chunk or iterating by keys with range, but sticking to the loop counter is perfectly valid and efficient for simple linear lists like $category_news. The key takeaway is ensuring the modulus condition matches the period of the pattern you are trying to enforce.

Handling the First Iteration

One edge case often overlooked in these scenarios is the very first item (index 0). If your logic depends on row classes being applied consistently, ensure that the initial <li class="row"> tag exists before the loop begins. In your original snippet, the opening <li> seems to be inside the conditional block if ($i % 3 == 2), which means it never renders until the third item is found. This results in a malformed HTML list where the first two items have no parent <li>.

To fix this, move the <li class="row"> opening tag to execute once before the loop starts. Then, use the modulus check strictly for closing tags or applying specific classes to the content divs. This separation of concerns—initialization versus iteration logic—makes the code easier to debug and maintain.

Our network