Php 在循环中创建HTML元素

Php 在循环中创建HTML元素,php,loops,Php,Loops,给定一个像这样的数字:6我需要生成6个DIV元素。 例如: $number = 6; // PHP generates the DIV for $number of times (6 in this case). 我怎么做?如果是这样的话,我不是PHP循环的专家。谢谢 可以使用的不同类型循环的示例用法。希望你能看到它们是如何工作的 Foreach循环 $element=”“; $count=6; foreach(范围(1,$count)为$item){ echo$元素; } While循环

给定一个像这样的数字:
6
我需要生成6个
DIV
元素。
例如:

$number = 6;
// PHP generates the DIV for $number of times (6 in this case).

我怎么做?如果是这样的话,我不是PHP循环的专家。谢谢

可以使用的不同类型循环的示例用法。希望你能看到它们是如何工作的

Foreach循环
$element=”“;
$count=6;
foreach(范围(1,$count)为$item){
echo$元素;
}
While循环
$element=”“;
$count=0;
而($count<6){
$count++;
echo$元素;
}
简单For循环
$element=”“;
$count=6;
对于($i=0;$i<$count;$i++){
echo$元素;
}

您需要echo命令。基本上,您是通过打印字符串来生成html的。范例

echo '<div> </div>';
echo';
将生成1个div。您需要它6次。您可能也想使用循环,但这是一个太基本的问题,我给了您一个开始。

函数generateDIVs($number)
function generateDIVs($number)
{
  for ($i = 0; $i <= $number; $i++)
  {
    echo "<div><div/>";
  }
}
{ 对于($i=0;$i
for($i=0;$i<6;$i++){
回声“;
}
请注意,id(
#
部分)在页面上必须是唯一的,因此不能有6个具有相同
#示例
id的不同div


以下是我经常使用的一些示例,用于在使用PHP时快速模拟重复的HTML

具有迭代索引和范围 使用的唯一一个小“缺点”是结尾的
EOT;
不能有前导空格和后导空格或制表符,这在结构良好的标记中可能看起来很难看,因此我经常将函数放在文档顶部,并在需要时使用

当不需要索引时
$html=”
一些内容
";
echo str_repeat($html,6);

为了生成6个div元素,需要循环

使用while循环:

$count = 1;
while($count <= 6){
    $count++;
    echo "<div></div>";
}
$count=1;
而($count)
echo '<div> </div>';
function generateDIVs($number)
{
  for ($i = 0; $i <= $number; $i++)
  {
    echo "<div><div/>";
  }
}
for ($i = 0; $i < 6; $i++) {
    echo "<div class=\"example\"></div>";
}
$html = function($i) {
  echo "
  <section class=\"fooBar\">
    The $i content
  </section>
  ";
};

array_map($html, range(0, 5));
$html = function($i) {
echo <<<EOT
  <section class="fooBar">
    The $i content
  </section>
EOT;
};

array_map($html, range(1, 6));
$html = "
  <section class='fooBar'>
    Some content
  </section>
";

echo str_repeat($html, 6);
$count = 1;
while($count <= 6){
    $count++;
    echo "<div></div>";
}
$count = 6;
for ($i = 0; $i < $count; $i++) {
    echo "<div></div>";
}