I have the following code:
for ($i = 0; $i < count($gallery); $i++)
{
$temp = array();
$temp = $gallery[$i];
echo "<img src='". $temp->path . "' />";
}
Now this code prints the content in one row. I want to print only 3 per row and then create new row and print another 3 and so on. How can this be done?
EDIT: error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 5
Filename: views/profile.php
Line Number: 105
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/profile.php
Line Number: 106
You can do
$n = 3;
echo "<table><tr>";
for($i=0; $i<count($gallery);$i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i % $n ==0 && $i!=0 ){
echo "</tr><tr>";
}
}
echo '</tr></table>';
Edit:
If you want to do it the "right" way - by building the syntactically correct HTML, you need to do:
$n = 3;
echo "<table><tr>";
$gallery_count = count($gallery);
for($i=0; $i<$gallery_count; $i++){
$temp = array();
$temp = $gallery[$i];
echo "<td><img src='". $temp->path . "' /></td>";
if($i != 0){
if($i % $n == 0 && $i != $gallery_count-1){
echo "</tr><tr>";
}
else{
echo ""; //if it is the last in the loop - do not echo
}
}
}
//example - if the last 2 `td`s are missing:
$padding_tds = $gallery_count % $n;
if($padding_tds != 0 ){
$k = 0;
while($k < $padding_tds){
echo "<td> </td>";
}
}
echo '</tr></table>';