Adding div after every two posts?

I am trying to add a div after every two posts, so that home.php looks like the following:

<div class="row">
<div class="col-sm-6-noGutter">..</div>
<div class="col-sm-6-noGutter">..</div>
</div>

I almost have it working, the only problem is that in the first “row” there are three posts and not two. I can´t really figure out why, but I guess the problem is in how i count the number of posts?

Here is the loop in my home.php

    <div class="center-row"><!--not dynamic-->
<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('templates/content', get_post_format()); ?>
  <?php if ( 0 !== $wp_query->current_post 
        && 0 == $wp_query->current_post%2
    ) {
        echo '</div><div class="center-row">';
    } ?>
<?php endwhile; ?>
</div><!--last row-->

PS: its been a long shitty day full of allergies, so if you don´t understand what I mean please tell me.

Very quick guess: PHP is a “zero based” language, right? That means, that indexes are counted from 0, not 1. That makes

$posts = array('post1','post2','post3');
print_r($posts);

as

array(
    [0] => 'post1',
    [1] => 'post2',
    [2] => 'post3',
)

, right?

@cibulka hit the nail on the head. This should have you sorted:

<div class="center-row"><!--not dynamic-->
  <?php while(have_posts()) : the_post(); ?>
    <?php get_template_part('templates/content', get_post_format()); ?>
    <?php if($wp_query->current_post > 0 && ( ($wp_query->current_post + 1) % 2 == 0) ) : ?>
      </div><div class="center-row">
    <?php endif; ?>
  <?php endwhile; ?>
</div><!--last row-->

What @cibulka said.

I use a slightly different method I found somewhere.


    $count = 0;
    
    // start the loop
    while(have_posts()) : the_post();
    
        // Create open wrapper if count is divisible by 2 (change '2' as needed)
        $open = !($count%2) ? '<div class="row">' : ''; 
    
        // Close the previous wrapper if count is divisible by 2 and greater than 0
        $close = !($count%2) && $count ? '</div>' : ''; 
    
        // Get it started.
        echo $close.$open;

            <div class="col-sm-6-noGutter">
                // .... do loop stuff here ....  //
            </div>
       
        $count++ 

    endwhile;

thank you guys for all the input!