是否有可用于此的操作数类型?

时间:2011-07-13 00:24:35

标签: php for-loop

看看这张表:

<?php
echo '<table>';
for($i = 1;$i<99;$i++)
{
  $i = intval($i);

  if ($i / 3  == intval($i / 3))
  {
    echo "<tr><td>this is third tr</td></tr>";
  }
  else
  {
     echo "<tr><td>this is first or second</td></tr>";
  }
}

输出类似于

this is first or second
this is first or second
this is third tr
this is first or second
this is first or second
this is third tr
this is first or second
this is first or second
this is third tr

是否有更优雅的方式来检测ALWAYS第三个tr?

2 个答案:

答案 0 :(得分:4)

你正在寻找类似的东西吗?

<?php
echo '<table>';
for($i = 1;$i<99;$i++){
  if ($i % 3  == 0){
    echo "<tr><td>this is third tr</td></tr>";
  }else{
     echo "<tr><td>this is first or second</td></tr>";
  };
};
echo "</table>";
?>

http://php.net/manual/en/language.operators.arithmetic.php

答案 1 :(得分:1)

使用modulus operator ...

if ( ! (i % 3))

它将返回除法的剩余部分。由于优先顺序,您需要括号。

CodePad

$i = intval($i)也是多余的。 $i已经是整数。