开发者

Create HTML elements in loop

开发者 https://www.devze.com 2023-03-30 12:36 出处:网络
Given a number like i.e: 6 I need to generate 6 DIV elements. For example: $number = 6; // PHP generates the DIV for $number of times (6 in this case).

Given a number like i.e: 6 I need to generate 6 DIV elements.

For example:

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

How can I do it? I am not开发者_Python百科 an expert of PHP loops, if this is the case. Thanks!


Example uses of the different types of loops you could use. Hopefully you can see how they work.

Foreach Loop

    $element = "<div></div>";
    $count = 6;
    foreach( range(1,$count) as $item){
        echo $element;
    }

While Loop

   $element = "<div></div>";
   $count = 0;
   while($count < 6){
       $count++;
       echo $element;
   }

Simple For Loop

$element = "<div></div>"; 
$count = 6;
for ($i = 0; $i < $count; $i++) {
    echo $element;
}


function generateDIVs($number)
{
  for ($i = 0; $i <= $number; $i++)
  {
    echo "<div><div/>";
  }
}


In order to generate 6 div elements loop is necessary.

using while loop:

$count = 1;
while($count <= 6){
    $count++;
    echo "<div></div>";
}

using for loop:

$count = 6;
for ($i = 0; $i < $count; $i++) {
    echo "<div></div>";
}


for ($i = 0; $i < 6; $i++) {
    echo "<div class=\"example\"></div>";
}

Note that IDs (the # part) have to be unique on a page, so you can't have 6 different divs with the same #example id.

http://php.net/manual/en/control-structures.for.php


Here are some examples I use often, for quick mock-upping repeated HTML while working with PHP

array_walk() with iteration index and range

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

If tired of escaping double quotes \" or using ' or concatenation hell, you could simply use Heredoc.

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

array_map($html, range(1, 6));

The only small "disadvantage" of using Heredoc is that the closing EOT; cannot have leading and following spaces or tabs - which might look ugly in a well structured markup, so I often place my functions on top of the document, and use <?php array_map($html, range(0, 5)) ?> where needed.

str_repeat() when an index is not needed

$html = "
  <section class='fooBar'>
    Some content
  </section>
";

echo str_repeat($html, 6);
    


you need echo command. Basically you are generating html by printing a string. Example

echo '<div> </div>';

will generate 1 div. You need it 6 times. You might want to use loop as well, but this is too basic question and I gave you a start.

0

精彩评论

暂无评论...
验证码 换一张
取 消