PHP Algorithm to Evenly Distribute Items into 3 Columns

Submitted by nigel on Tuesday 9th November 2010

This is the second time in my PHP career I've needed this so thought I'd commit it to a blog for easy access next time and save myself some brain MIPS. I want to evenly distribute items into three piles, making sure that no pile can have more than 1 extra item, and should a pile need 1 more than the other piles, then the item should go to the left-most first. This is better explained by way of a diagram. My pile of items is shown as letters of the alphabet.

A A
AB A,B
ABC A,B,C
ABCD AB,C,D
ABCDE AB,CD,E
ABCDEF AB,CD,EF
ABCDEFG ABC,DE,FG
ABCDEFGH ABC,DEF,GH
ABCDEFGHI ABC,DEF,GHI
ABCDEFHGIJ ABCD,EFG,HIJ
ABCDEFHGIJK ABCD,EFGH,IJK

Ok, the actual solution isn't particularly difficult, but it needed a little contemplation. Reproduced below we have the answer.

<?php
    $count 
count($rows);
    
$columns 3;
    
$col1 floor(($count $columns 1) / $columns);
    
$col2 floor(($count $columns 2) / $columns);
    
$col3 floor(($count $columns 3) / $columns);
?>
Here we are saying that the count for each column is held in $col1, $col2 and $col3 respectively. Done
blog terms
PHP