MIC*_*MIC 2 php each loops if-statement modulus
我有一些循环.如何优化此代码,从第2项开始每12项执行一次.我正在为每个+12项使用硬编码的代码,但当然这不是一个好的解决方案:)我知道这很容易做,我试图用模数运算符来做,但它的工作方式不正确.
<?php if( ($counter == 2) || ($counter == 14) || ($counter == 26) || ($counter == 38) || ($counter == 50) || ($counter == 62) || ($counter == 74) || ($counter == 86) || ($counter == 98 .... ?>
Run Code Online (Sandbox Code Playgroud)
感谢帮助!
回答
看一下Modulus运算符(%):
<?php
if ( ( $counter - 2 ) % 12 == 0 ) {
//....
}
?>
Run Code Online (Sandbox Code Playgroud)
说明
模数运算符(
$a % $b)是$a除以的余数$b.
$counter - 2- 当您从偏移量开始时2,将其从中删除$counter% 12- 将返回$counter - 2除以的余数12== 0- 如果上面的返回0,你知道它是完全可分的