[英]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.