Dejavu
Dejavu

Reputation: 713

calculate specific values of counter inside foreach loop

I am trying to calculate specific values of a counter in my foreach loop.

I have this if statement in my code

if ( $i == 21 || $i == 41 || $i == 61 || $i == 81 || $i == 101 )

which are equal to

($i * 20) + 1

Instead of writing all these values (21,41,61,81...) I want to create a formula for my code but I couldn't figure out what the result should be equal to inside my if statement

Upvotes: 0

Views: 39

Answers (2)

Matiu Carr
Matiu Carr

Reputation: 298

Look for the remainder after dividing by 20 using the % operator (modulus).

if ($i%20 == 1)
{
    // do stuff
}

Upvotes: 0

rjdown
rjdown

Reputation: 9227

Use modulus:

if ($i % 20 == 1) { ...

http://php.net/manual/en/language.operators.arithmetic.php

Upvotes: 3

Related Questions