PHP Split column when item = 4
I have an array, and now I am putting this array in for loop
to show every item in this array, but I want to set an item limit (4 items in each column), here is my code.
<?php
$area = $custom_area_settings; //is an array with 5 element
for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
if($area->custom_area_list[$i]->top_show):
echo '<div class="sub-column column'.$i.'">';
echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
echo '</div>';
endif;
endfor;
?>
In this code, a div has column$i
created every time loop, but I just want this div to be created when the loop runs 4 times, after 4 times this div is created again, after 8 times this div will be created again and continue ...
Here is the result I want.
Column 1 Column 2
--------------- ---------------
item 1 item 5
item 2 item 6
item 3 item 7
item 4 item 8
Here is the result I am getting now
Column 1
---------------------
item 1
Column 2
---------------------
item 2
.....
Please, help.
source to share
<?php
$area = $custom_area_settings; //is an array with 5 element
$i=0;
echo '<div class="sub-column column'.$i.'">';
for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
if($area->custom_area_list[$i]->top_show):
if($i%4 === 0):
echo '</div>';
echo '<div class="sub-column column'.$i.'">';
endif;
echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
endif;
endfor;
echo '</div>';
?>
source to share
Updated:
$html = $i%4 === 0 ? '<div class="sub-column column'
. $i . '">'
. '{1}' . '</div>' : '{1}';
echo strtr($html,array('{1}' => '<p class="line"> '
. $area->custom_area_list[$i]->header
. '</p>'
));
% divides $ i by 4 and returns the remainder, which should be 0 in this case
source to share
I would recommend that you use the command array_chunk
Example
$chunkedArray = array_chunk(['One', 'Two', 'Three', 'Four', 'Five'], 4);
echo '<div class="row">';
array_walk( $chunkedArray, function($array)
{
echo '<div class="col-md-4">'
foreach( $array as $key => $value )
{
echo "<p class='line'>$value</p>";
}
echo '</div>';
});
echo '</div>';
This example was created using twitter bootstrap css classes. I'm sure it can be optimized just by demonstrating the array_chunk approach.
source to share