PHP foreach loop with w3 responsive grid
Make sure to include the Bootstrap stylesheet in your HTML to access its grid classes. You can do this by adding the following line in the section of your HTML file:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
Let's assume you have an array, $myArray, containing items you wish to display in a responsive grid. In our example, we'll structure this array and break it into rows of four columns each, aligning with Bootstrap's grid structure.
<?php
$myArray = ['Item-1', 'Item-2', 'Item-3', 'Item-4', 'Item-5', 'Item-6', 'Item-7', 'Item-8'];
$myArray = array_chunk($myArray, 4);
foreach($myArray as $Array){
echo '<div class="row">';
foreach($Array as $Value){
echo '<div class="col-md-3">'.$Value.'</div>';
}
echo '</div>';
}
?>
Here, array_chunk is employed to create sub-arrays, each containing four elements. The outer foreach loop iterates through these sub-arrays, generating Bootstrap rows. The inner loop then populates each row with individual items in Bootstrap's grid columns.