Aaron Reisman
Aaron Reisman

Reputation:

How to perform an action every 5 results?

How can I perform an action within a for loop every 5 results?

Basically I'm just trying to emulate a table with 5 columns.

Upvotes: 15

Views: 24105

Answers (6)

shdw
shdw

Reputation: 1

This works to get a live index within the foreach loop:

<?php

// Named-Index Array
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic', 'test' => 'one two', 'potato' => 'french fries', 'tomato' => 'ketchup', 'coffee' => 'expresso', 'window' => 'cleaner', 'truck' => 'load', 'nine' => 'neuf', 'ten' => 'dix');

// Numeric-Index Array of the Named-Index Array
$myNumIndex = array_keys($myNamedIndexArray);


foreach($myNamedIndexArray as $key => $value) {
    $index = array_search($key,$myNumIndex);

    if ($index !== false) {
        echo 'Index of key "'.$key.'" is : '.$index.PHP_EOL;

        if (($index+1) % 5 == 0) {
            echo '[index='.$index.'] stuff to be done every 5 iterations'.PHP_EOL;
        }
    }

}

Upvotes: 0

Jose
Jose

Reputation: 13

// That's an easy one

for($i=10;$i<500;$i+=5)
{
    //do something
}

Upvotes: -2

redcayuga
redcayuga

Reputation: 1251

Another variation:

int j=0;
for(int i = 0; i < 500; i++) 
{ 
    j++;
    if(j >= 5) 
    { 
        j = 0;
        //do your stuff here 
    } 
}

I'm old fashioned, I remember when division took a long time. With modern cpus it probably doesn't matter much.

Upvotes: 0

patros
patros

Reputation: 7819

It's possible to use a condition with a modulus, as pointed out. You can also do it with nesting loops.

int n = 500;
int i = 0;

int limit = n - 5
(while i < limit)
{
   int innerLimit = i + 5
   while(i < innerLimit)
   {
       //loop body
       ++i;
   }
   //Fire an action
}

This works well if n is guaranteed to be a multiple of 5, or if you don't care about firing an extra event at the end. Otherwise you have to add this to the end, and it makes it less pretty.

//If n is not guaranteed to be a multiple of 5.
while(i < n)
{
  //loop body
  ++i;
}

and change int limit = n - 5 to int limit = n - 5 - (n % 5)

Upvotes: 0

Steve
Steve

Reputation: 4213

For an HTML table, try this.

<?php
$start = 0;
$end = 22;
$split = 5;
?>
<table>
    <tr>
  <?php for($i = $start; $i < $end; $i++) { ?>
    <td style="border:1px solid red;" >
         <?= $i; ?>
    </td>
    <?php if(($i) % ($split) == $split-1){ ?>
    </tr><tr>
    <?php }} ?>
    </tr>
</table>

Upvotes: 2

John Boker
John Boker

Reputation: 83709

you could use the modulus operator

for(int i = 0; i < 500; i++)
{
    if(i % 5 == 0)
    {
        //do your stuff here
    }
}

Upvotes: 50

Related Questions