I have an array of objects in which I want to iterate them in a foreach loop. However I want to only allow for 3 of them to be in a row and then after the 3rd, a new row to start, and so on.
function displayIncomeDetails($deets) { $result = NULL; if($deets != NULL) { foreach($deets as $deet) { $result .= ' <div class="row mt-4"> <div class="col-sm-3"> '.$deet.' </div> </div> '; } } else { $result = ' <div class="row"> <p style="margin: 0 auto;" class="mt-4 text-danger">No Details Found</p> </div> '; } return $result; }
So instead of 1 column in the row I would like 3
Advertisement
Answer
array_chunk
is very usable here, e.g.:
foreach (array_chunk($deets, 3) as $perRow) { $result .= '<div class="row mt-4">'; foreach ($perRow as $deet) { $result .= '<div class="col-sm-3">' . $deet . '</div>'; } $result .= '</div>'; }