Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Array Into 3 Equal Columns With PHP

Tags:

foreach

php

I'm using the following PHP code to echo the data from an array...

foreach($businessnames as $b)
{
    $theurl = get_term_link($b, 'businessnames');
    echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
}

I was using this to get the data into 3 equal columns but now I need to do 3 equal columns in the order from the array (as opposed to "left to right" like CSS floats cause). I imagine I need to count the total values in the array with PHP and then divide that, but I'm not sure what the code would be. I've been looking around but haven't found something that addresses this in particular.

How could I adapt my code here to put the array's data into 3 equal columns?

Thanks!

like image 520
user1364769 Avatar asked Jan 20 '26 18:01

user1364769


1 Answers

You can use array_chunk to split an array into pieces

$cols = array_chunk($businessnames, ceil(count($businessnames)/3)); 

foreach ($cols as $businessnames){
    echo "<ol class='col'>";
    foreach($businessnames as $b)
    {
        $theurl = get_term_link($b, 'businessnames');
        echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
    }
    echo "</ol>";
}

Alternatively you can use a pure css solution.

echo "<ol style='column-count:3; -o-column-count:3; -moz-column-count:3; -webkit-column-count:3;'>";
foreach($businessnames as $b)
{
    $theurl = get_term_link($b, 'businessnames');
    echo "<li style='width: 31%;'><a href=\"" . $theurl . $append . "\">". $b->name ."</a></li>";
}
echo "</ol>";
like image 57
Orangepill Avatar answered Jan 23 '26 07:01

Orangepill