[英]Matching variable to every 4th number in a loop - PHP
我需要在循环遍历的第4个项目的末尾添加一个不同的类。 我这样做的方法是:
$i=0;
foreach($mount as $m){
$i++;
$startClass = '';
if($i==4||$i==8||$i==12){$startClass='<div with class>';} //adds class on 4th intervals
$ret.=''.$startClass.'<other HTML here and such>'; //shorted for readability
}
现在,鉴于以下事实,如果我的循环包含40个对象,则需要相应地调整if
语句,我确定有一种更合适的方法来处理此问题。
我回想起可能有用的算术公式[an = a1+(n-1)d]
但发现我的想法似乎错了。 我将其应用(用i代替an),它将始终=等式,因此每个项目都获得该类。
有什么建议么? 提前致谢!
使用模数运算符http://www.php.net/manual/zh/language.operators.arithmetic.php
if(($i % 4) === 0){
//add class
}
将foreach
控件结构和%
模数运算符结合使用,将为您提供所需的内容:
foreach ($mount as $key => $m) {
if ($key % 4 == 0) {
$startClass = '<div with class>';
} else {
$startClass = '';
}
$ret.=''.$startClass.'<other HTML here and such>';
}
foreach
哈希火箭( =>
)表示法使您可以传递要迭代的当前元素的索引。 您可以使用索引来跟踪第n个对象 。
模运算符返回除法运算的余数; 如果余数为零,则除数是除数的一个因数,因此可用于计算第n个因数。
您正在寻找的是模运算符
例:
if($i%4 == 0){$startClass='<div with class>';}
这意味着i = k + 0 , k是整数
$i=0;
foreach($mount as $m)
{
if (($i++ % 4) == 0)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.