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.
Author:
Jonas John
License:
Public Domain
Language:
PHP
Created:
07/19/2007
Updated:
01/10/2008
Tags:
array functions
/* 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; }
// The example works the same with the // array_chunk build-in function // Input array $InputArray = array(1, 2, 3, 4, 5, 6); // Split the array into two parts $Result = ArraySplitIntoParts($InputArray, 2); print_r($Result); /* Result will contain: Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) ) */
Feel free to leave a message:
Add a comment
array_chunk();
Thanks