Home > Enterprise >  How to get cyclical values on every foreach loop iteration
How to get cyclical values on every foreach loop iteration

Time:07-02

sorry for the title but I don't know how to explain it well in few words.

I'm dealing with a php loop where I need to get particular css classes names and other stuff (such as different svg elements) at each group of 4 iteration. This is what I need to obtain:

  1. iteration 1 = class 1
  2. iteration 2 = class 2
  3. iteration 3 = class 3
  4. iteration 4 = class 4
  5. iteration 5 = class 1
  6. iteration 6 = class 2
  7. iteration 7 = class 3
  8. (etc...)

Actually I'd like to post my attempt to get this, but this time I do not know where to begin (but probably I'm getting lost in a glass of water). Any suggestion or hints are more than welcome...

CodePudding user response:

You can use the Modulo (%) operator:

for ($i = 0; $i < 40; $i  ) {
    $id = ($i % 4)   1;
    $classname = "class{$id}";
    echo "$classname\n";
}

When you have an array of (class) names you want to use, then:

$classnames = ["class 1", "class 2", "class 3", "class 4"];
$n = count($classnames);

for ($i = 0; $i < 40; $i  ) {
    $index = $i % $n;
    $classname = $classnames[$index];
    echo "$classname\n";
}

CodePudding user response:

In a foreach loop it would be: the array index % 4 1, to get the repeating integer sequence 1,2,3,4.
But, if you have an array of classNames in the order you want them repeated you can do something like this:

$classNames = ['won','too','tree','fower'];
$array = [1,2,3,4,5,6,7,8,9];

foreach( $array as $index => $value ){
    $cssClass = $classNames[$index % count($classNames)];
    
    echo $cssClass.",";
}

Output for the above:

won,too,tree,fower,won,too,tree,fower,won,

Anytime you whish to change that sequence you simply have to edit the $classNames array, nothing more.

  • Related