PHP if is a multiple of an integer

后端 未结 5 1912
遥遥无期
遥遥无期 2021-01-25 08:55

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;          


        
相关标签:
5条回答
  • 2021-01-25 09:16
    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

    0 讨论(0)
  • 2021-01-25 09:18
    if(($i+1)%3 == 0){
        //do something
    }
    

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

    0 讨论(0)
  • 2021-01-25 09:18

    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!

    0 讨论(0)
  • 2021-01-25 09:29

    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.

    0 讨论(0)
  • 2021-01-25 09:34

    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 ||.

    0 讨论(0)
提交回复
热议问题