Help needed with array chunk

Hi everyone,

I’m hoping someone could please assist me with the following. I’d like to split the contents of an array into 2 equal columns. Each column should have a <div class=“stylecol”>'; followed by half of the array’s contents.

$explode = explode("-", $row['names']);
$chunk = array_chunk($explode, 2);
foreach ($chunk as $con ) {
echo '<div class="stylecol">
<p>'.$con.'</p>
</div>';
}

Something isn’t working…

Thank you in advance!

You’ve told it you want the array split into groups of two like
a,b
c,d
e,f
g,h
i,j

but you’re looking for two groups, right?
a,b,c,d,e
f,g,h,i,j

I think maybe array_chunk() is not what you want. You didn’t say what you’re expecting so my assumptions might be off but maybe this can get you started if so.


$explode = explode("-", $row['names']);
$final = array();
$n = floor( count( $explode ) / 2 );

$final[] = array_slice( $explode, 0, $n );
$final[] = array_slice( $explode, $n );

foreach( $final as $col ) {
  echo '<div class="stylecol">';
  foreach( $col as $name ) {
    echo "<p>{$name}</p>";
  }
  echo '</div>';
}

I used array_slice() to cut the array into two pieces. I put those two arrays into a containing array so that we can loop through it and create a div for each piece.

Hi QMonkey,

thanks a lot! I’ll try out the code a bit later.

Hello QMonkey,

your code is working perfectly. Thank you for taking the time to help me out! :tup: