0

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

2 Answers 2

3

Use modulus:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

does it output these values ? (21,41,61,81...)
It will calculate if $i is 21, 41, 61 or 81. Note that it will also match 1, so you might want if ($i % 20 == 1 && $i > 1) { if you do not want to include it.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.