JimmyBanks
JimmyBanks

Reputation: 4698

PHP if is a multiple of an integer

Within a for loop, i need to add some HTML that outputs only when the loop is on a [(multiple of 3) minus 1].

For example, what i could do is:

for($i=0; $i<count($imagearray); $i++)
{
    if($i=="0" || $i=="2" || $i=="5" || $i=="8" || $i=="11")
    {
        echo 'string';
    }
}

but this isnt very elegant and extremely useless for big for loops, is there a proper way to do this?

Upvotes: 1

Views: 5554

Answers (5)

JoeCortopassi
JoeCortopassi

Reputation: 5093

if ( $i==0 || ($i+1)%3 == 0 )
{
    //do stuff
}

What this will do, is go to the next index, divide it by 3, and see if there is a remainder. If there is none, then that means that the current index is one less than a number that is divisible by 3

Upvotes: 7

Andrew Willis
Andrew Willis

Reputation: 2349

the most elegent method is thus

if ($i % 3 === 2) {
  //do stuff
}

as it doesn't add things to the $i value, but all answers are essentially correct!

Upvotes: 0

VoronoiPotato
VoronoiPotato

Reputation: 3173

if(($i+1)%3 == 0){
    //do something
}

The % operator is known as the modulus operator and returns the remainder of a division.

Upvotes: 0

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

You want to use the modulo for that:

(1 % 3) == 1
(2 % 3) == 2
(3 % 3) == 0
(4 % 3) == 1

Good luck

Modulo is the same thing as saying, give me the remainder of a division. So 1 / 3 equals 0 remainder 1, and so on.

Upvotes: 0

Quentin
Quentin

Reputation: 943510

Use the modulus operator.

if (! (($i+1) % 3) ) {

If $i+1 divides into 3 with no remainder, the result will be zero. Then you just need a boolean not.

If you want to match 0 as well (since you use it in your example, but it doesn't match your description) then you will have to special case it with an ||.

Upvotes: 0

Related Questions