venom_1979
venom_1979

Reputation: 55

For Loop - Do Something Once Loop Hits Certain Number PHP

I'm working on a project for a real estate website. I have a function that uses a for loop to grab a row of data from the database for each available property. Normally this works perfectly but for this particular site the properties are displayed in rows of three. This means that once I have outputted 3 properties, I need to close the current div and open another div to display the next row of 3 properties. So essentially I need the loop to recognize once it hits three rows, echo something like

</div><div class="new div">

Then pick back up where it left off. My for loop currently looks like this:

function showFeaturedHomes() {
    $fetcher = $this->startDataFetch();
    for ($idx = 0; $idx < 30; $idx++)
    {   
        $row = $fetcher->fetch_assoc();
        if (!$row)
            break;
        $retVal .= $this->showBlock($row);
    }
    return ($retVal);

I've tried using the modulus operator(%) to detect once it hits a multiple of 3 and while it seems like it works, it's outputting the closing and opening divs BEFORE it does anything else, so I still end up in the same situation.

I hope I've been clear enough about what I'm trying to do, but if not please feel free to ask me for more info. Your help is very much appreciated! Thanks!

Upvotes: 2

Views: 103

Answers (1)

Jacek Kowalewski
Jacek Kowalewski

Reputation: 2851

function showFeaturedHomes() {
    echo '<div class="new div">'; // !!!
    $fetcher = $this->startDataFetch();
    for ($idx = 0; $idx < 30; $idx++)
    {
        if ($idx != 0 && $idx % 3 == 0) echo '</div><div class="new div">'; // !!!
        $row = $fetcher->fetch_assoc();
        if (!$row)
            break;
        $retVal .= $this->showBlock($row);
    }
    echo '</div>'; // !!!
    return ($retVal);
}

I dont know if you are returning values through echo and what does showBlock do, but the idea is clear here :). You were close with modulo! Best regards!

Upvotes: 1

Related Questions