2

I'm pretty new to PHP and am looking into using array_chunk() to split an array into three parts to display it as a three column list. Let's say I have an array like this

 $input_array = array('a', 'b', 'c', 'd', 'e', 'f');
 $chunks = array_chunk($input_array, 3, true));

and I want to output something like:

<div class="left">
 <ul>
  <li>a</li>
  <li>b</li>
 </ul>
 </div>

<div class="middle">
 <ul>
  <li>c</li>
  <li>d</li>
 </ul>
 </div>

<div class="right">
 <ul>
  <li>e</li>
  <li>f</li>
 </ul>
</div>

I've seen some really helpful examples on here but none that show how to foreach loop each chunk of the original array to place where you need within your html/css.

Is this a job for array_slice? But what if my array is dynamically populated and I don't know how big it will be at a given time?

Thanks!

Community
  • 1
  • 1
Erik Berger
  • 599
  • 1
  • 10
  • 24

2 Answers2

6
$div_class = array("left","middle","right"); 
$input_array = array('a', 'b', 'c', 'd', 'e', 'f');
$chunks = array_chunk($input_array, 2);

foreach($chunks as $i => $mychunk)
{
    echo "<div class=\"$div_class[$i]\">";
    echo "<ul>";

    foreach($mychunk as $newchunk) 
    {
    echo "<li>";
    echo $newchunk;
    echo "</li>";
    }

    echo "</ul>";
    echo "</div>";
}

Output -

<div class="left">
<ul>
<li>a</li>
<li>b</li>
</ul>
</div>
<div class="middle">
<ul>
<li>c</li>
<li>d</li>
</ul>
</div>
<div class="right">
<ul>
<li>e</li>
<li>f</li>
</ul>
</div>
fsasvari
  • 1,891
  • 19
  • 27
swapnesh
  • 26,318
  • 22
  • 94
  • 126
1

Your array_chunk($input_array, 3, true)) code returns the chunk with three values but according to your output that you expected you have to set array_chunk($input_array, 2, true)

to follow the link to know more about array_chunk()

$input_array = array('a', 'b', 'c', 'd', 'e', 'f');
$chunks = array_chunk($input_array, 2, true);

//print_r($chunks);
for( $i=0;$i<count($chunks);$i++ ){
   echo "<div>\n";
   echo "<ul>\n";
   foreach( $chunks[$i] as $k=>$v ){

     echo "<li>$v</li>\n";

   }
  echo "</ul>\n";
  echo "</div>\n\n";
 }

to see the output check the following link http://codepad.org/8K1luela

jogesh_pi
  • 9,762
  • 4
  • 37
  • 65
  • this works except for it doesn't place each "chunk" in the named div (left, middle, right). Still helpful though! – Erik Berger Feb 05 '13 at 04:36