I am trying to create some HTML using php/mysql.
My HTML should be something like below:
<div class="row">
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
</div>
<div class="row">
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
</div>
..........
<div class="row">
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
<div>Content Block</div>
</div>
There are 4 content divs in each row.
This is how I tried it in my PHP while loop, but its not work for me.
while($stmt->fetch()) {
if($i % 4 == 0) {
$html = "<div class='row'>\n";
}
$html .= " <div class='checkbox col-sm-3'>\n";
$html .= " <label>\n";
$html .= " <input class='custom' name='facility[$fid]' type='checkbox'>\n";
$html .= " <span class='lbl'> {$fname}</span>\n";
$html .= " </label>\n";
$html .= " </div>\n";
if($i++ % 4 == 4) {
$html .= " </div>\n";
}
$ckbxOurPut[] = $html;
}
Can anybody tell me what it the wrong with this?
Thank you.
5 Answers 5
if($i++ % 4 == 4) {
$var % 4 can never be 4. What you want is this:
if($i++ % 4 == 3) {
Edit: also in line 4 you redefine $html, when you should just concatenate (.= operator)
2 Comments
$ckbxOurPut[] = $html; is another problemFirst, you have to change if($i++ % 4 == 4) to if($i++ % 4 == 3)
Also, on line 4 of your code, you use $html = "<div class='row'>\n"; instead of $html .= "<div class='row'>\n";.
Comments
Make this changes 1. Modulus changes 2. Push html in array after outer div close.
if($i++ % 4 == 3) {
$html .= " </div>\n";
$ckbxOurPut[] = $html;
}
Comments
<?php
$a = [
1,2,3,4,5,6,7,8,9,0,11,12,13
];
$i = 0;
$html = "";
foreach($a as $val)
{
if($i % 4 == 0) {
$html .= "<div class='row'>\n";
}
$html .= $val."\n";
if($i++ % 4 == 3) {
$html .= " </div>\n";
}
}
if($i % 4 != 3) {
$html .= " </div>\n";
}
echo $html;
Try this:
$i = 0;
$html = "<div class='row'>";
while($stmt->fetch()) {
$i++;
if($i == 5) {
$html .= "</div><div class='row'>";
$i = 1;
}
$html .= " <div class='checkbox col-sm-3'>\n";
$html .= " <label>\n";
$html .= " <input class='custom' name='facility[$fid]' type='checkbox'>\n";
$html .= " <span class='lbl'> {$fname}</span>\n";
$html .= " </label>\n";
$html .= " </div>\n";
}
$html .= "</div>";
echo $html;
.rowdiv.$ckbxOurPutand why it is inside loop ?