Code Lover
Code Lover

Reputation: 8368

PHP After every NTH in DIV LOOP

Hi I want to add content after every 3rd div in the loop. Here is below code but I am not getting even render content "Hi this is the 3d div"

Its not detecting every 3rd div.

<?php
    function q_list_item($q_item)
    {
        $count = 0;

        $this->output('<DIV>');
        $this->my_items;    
        $this->output('</DIV>');

        $count++;           

        if($count % 3 == 0) {
            echo 'Hi this is the 3rd div';
        }

    }
?>

----[Actual Function]-----------------------------------------------

<?php

function q_list_item($q_item)
{

    $this->output('<DIV CLASS="qa-q-list-item'.rtrim(' '.@$q_item['classes']).'" '.@$q_item['tags'].'>');

    $this->q_item_stats($q_item);
    $this->q_item_main($q_item);
    $this->q_item_clear();

    $this->output('</DIV> <!-- END qa-q-list-item -->', '');

}
?>

Upvotes: 0

Views: 1189

Answers (2)

Mike
Mike

Reputation: 781

<?php
    $count = 0;
    function q_list_item($q_item)
    {
        $this->output('<DIV>');
        $this->my_items;    
        $this->output('</DIV>');

        $count++;           

        if($count % 3 == 0) {
            echo 'Hi this is the 3rd div';
        }

    }
?>

initialize the $count outside the loop, otherwise count will always be 1 when it reaches the if statement

Upvotes: 0

Fenton
Fenton

Reputation: 251162

You are resetting the $count to 0 at the top of this function, so it will always be 1 when you run the if statement at the end of the function.

This may help with your issue, although I can't tell if your code is in a class or not as it doesn't look like it is, but you are using $this-> in there. Essentially, move the instantiation of the counter outside of the function:

<?php
    $q_list_count = 0;

    function q_list_item($q_item)
    {
        $q_list_count++;

        $this->output('<DIV>');
        $this->my_items;    
        $this->output('</DIV>');

        if($q_list_count % 3 == 0) {
            echo 'Hi this is the 3rd div';
        }

    }
?>

Upvotes: 2

Related Questions