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 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.
$element = "<div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element;
}
$element = "<div></div>";
$count = 0;
while($count < 6){
$count++;
echo $element;
}
$element = "<div></div>";
$count = 6;
for ($i = 0; $i < $count; $i++) {
echo $element;
}
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.
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);
returning inside the callback of array_map(), then you probably shouldn't be using array_map(). In these instances, array_walk() is usually more appropriate since it doesn't expect anything to be returned.