1

Possible Duplicate:
php split array into smaller even arrays

How can I slice an array into multiple parts ? Lets say I have this array:

$arr = range(1, 15);

How can I end up with this result :

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
       ............
)

What I've tried so far :

$parts = 3;
$slices = array();

for($i=0; $i<($parts * $parts); $i=$i+$parts){
  $sliced = array_slice($arr, $i, (count($arr) / $parts));
  array_push($slices, $sliced);
}

It seems to be working fine only with arrays under 10 elements that makes me confused about why and how that code works really, it doesn't seem static to me as well.. Is there any other way to do it or a fix for the code?

Community
  • 1
  • 1
Osa
  • 1,922
  • 7
  • 30
  • 51

1 Answers1

7

You can use the built-in function array_chunk instead of writing your own:

$chunks = array_chunk($arr, 3);