php - 每 3 次迭代中断 while 循环

标签 php html css

我正在使用此 PHP 生成 0-9 的列表。

$counter = 0; 
WHILE ($counter < 10) 
{ 
  print "counter is now " . $counter . "<br>"; 
  $counter++; 
}

我想改变它的工作方式。每第 3 次迭代,我想将打印的文本包装在 <div> 中如果可能的话。

所以最终我输出的代码是:

<div>
counter is now 0
counter is now 1
counter is now 2
</div>
<div>
counter is now 3
counter is now 4
counter is now 5
</div>
<div>
counter is now 6
counter is now 7
counter is now 8
</div>
<div>
counter is now 9
</div>

最佳答案

使用模数运算符,您可以每 3 次迭代拆分输出,但您仍然需要检查可能生成空 div block 的 limit

<?php

$counter = 0; 
$limit = 10;

print "<div>\n";

while ($counter < $limit) { 
  print "counter is now " . $counter . "<br>\n"; 

  if (++$counter % 3 === 0 && $counter < $limit) {
    print "</div>\n<div>\n";

  }
}
print "</div>\n";

关于php - 每 3 次迭代中断 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28542890/

相关文章:

javascript - 侧边栏和主页持久性 - Rails

android - 用于网页的 CardView

css - gwtbootstrap3。如何用按钮调整 ButtonGroup 元素

php - 使用 PHP 按周分组和显示 MySQL 条目

php - 在 slider 中创建半透明文本背景

javascript - 鼠标悬停功能不创建弹出窗口

html - 如何在按钮内居中放置超赞字体图标?

php - 在 Zend Framework 2 Select 中左连接变量

javascript - 无法从 phpmyAdmin 数据库表检索问题/信息

javascript - 如何设计自定义文件上传按钮,以便标签在文件上传时发生变化