Using Wordpress and PHP, I want to write a couple of for loops that will allow me to output html with bootstrap to create a grid of images from a gallery in the back end rather than coding all of the images into the page individually. The outer for loop works and creates the two bootstrap divs. It’s the if statement within the inner loop that is posing the problem for me.
I was last attempting to get the if statement to end the inner loop early at element 4 and fall out into the outer loop which would close the first div. After that the outer loop would start again, creating another div, but I couldn't figure out how to restart the inner loop at element 5 in the test array.
What do I need to make this for loop stop filling the first div with content after number 4 and end the first div, but will start again at number 5, starting the second div and run the rest of the loop?
Right now this is what I have. I'm using a numerical array as a test to get the loops working.
<?php $arr = array(1, 2, 3, 4, 5, 6, 7, 8);
$length = count($arr);
?>
<div class="row w-100">
<?php for($i = 1; $i <= 2; $i++) //Outer loop
{
?>
<div class="row w-100">
<?php
for($j = 0; $j <= $length; $j++) //Inner loop
{
if($j == 4)
{
break;
}
else
{
echo $arr[$j];
}
}
?>
</div>
<?php
} //End outer loop
?>
</div>
When the inner loop outputs content into the divs it looks like this:
1234 <—Div 1
1234 <—Div 2
This is what I want it to look like:
1234 <—Div 1
5678 <—Div 2
In one attempt I used a foreach loop as the inner loop, but I learned that you can't stop a foreach loop and start it again at an index so I abandoned that for two for loops instead.
I also realize that a break statement is not the best solution. It's just there to show my current progress. I tried a continue statement, but my result printed out the entire array for both divs while skipping number 5.
Aucun commentaire:
Enregistrer un commentaire