PHP equivalent of nth-child

I have a PHP array of items (WordPress posts) that I loop through to create a 3×3 grid of posts.
Using jQuery, I apply a CSS class to the middle-column items like so:
$('#grid li:nth-child(3n+2)').addClass('middle');

How can I achieve this in PHP? Can I set a counter that will match 2,5,8,11, etc...?

Related posts

Leave a Reply

4 comments

  1. Do you know about loops in PHP? Without knowing more about what exactly you’re trying to achieve in your PHP code, I can only suggest something like this:

    $posts = array(); //The whatever thing that contains the posts you are concerned about
    for ($i = 1; $i<=count($posts); $i++) {
        if($i == /*selector condition*/) {
            //do what you do with the targeted posts
        } else {
            //do what you do with all others
        }
    }
    

    (See http://www.w3schools.com/php/php_looping_for.asp)

    Little side note: You would normally start counting with $i=0 but I assume if you’re talking about posts they will probably start counting at 1 and not 0.

  2. function nthChild($multiplier, $addition, $max)
    {
        $validInedexes = array();
    
        for ($n = 0; $n < $max; $n++)
        {
            $idx = $multiplier * $n + $addition;
            if ($idx > $max)
            {
                return $validInedexes;
            }
            $validInedexes[] = ($idx - 1);
        }
    }
    

    The above function will give you valid indexes based on input.
    Then in any loop match by index. use in_array function for that or anything you like.

  3. $my_query = new WP_Query(‘category_name=special_cat&posts_per_page=10’); ?>

    $query = new WP_Query('...');
    $posts = ($count = $query->post_count) ? range(1, $count) : array();
    foreach (array_chunk($posts, 3) as $row => $rowIndexes)
    {
        foreach ($rowIndexes as $column => $index)
        {
            $query->the_post();
            $middle = $column === 1;
            ...
        }
    }
    
  4. :nth-child(3n+2) would be:

    $count = count($arr);
    for($i = 0, $idx = 0; $idx < $count - 1; $idx = 3 * $i + 2, $i++) {
        print_r($arr[$idx]);
    }
    

    Granted this will only give you those specific items. If you wanted all the items and only run a block of code on those elements then I don’t know…. yet.