Split an array into chunks

This function splits a array into a given size.
This can be useful for creating columns or dividing a list in multiple parts.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
07/19/2007

Updated:
01/10/2008

Tags:


/*
 
Oops - the method I created did already exist as
build-in function, it may be better to use the 
internal function than mine:
 
array array_chunk ( array $input, int $size [, bool $preserve_keys] )
 
Thanks to Nick for the notice!
 
*/
 
 
//
// My old method (just as example or to customize it):
//
function ArraySplitIntoParts($Array, $Divider){
    $NewArray = array();
 
    // Half of all entries (count)
    $Half = round(count($Array) / $Divider);    
    $Pos = 1; $Area = 0;
 
    while(list($Key, $Value) = each($Array)){
 
        if ($Pos > $Half){    
 
            // Next field
            if ($Area < $Divider - 1)
                $Area++;            
 
            // Reset position
            $Pos = 1;
        }
 
        $NewArray[$Area][] = $Value;
        $Pos++;
    }
 
    return $NewArray;
}
 
// Another, even shorter function 
function ArraySplitIntoParts_Shorter($array, $step){
    $new = array();
 
    $k = 0;
    for ($x=0; $x < count($array); $x++){
        if (!($x % $step)){ $k++; }
        $new[$k][] = $array[$x];
    }
 
    return $new;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

Etheco August 26, 2009 at 09:10
Nice Function but do you know PHP already has a funtion to split a array into chunks.

array_chunk();
Mehanathen N December 17, 2008 at 12:44
Thanks and it was very use full
I.Iyngaran December 05, 2008 at 15:38
Congrats!!!, very usefull.
Thanks