split php array into smaller chunk

In this post we will splitting an php array into smaller chunk might be useful for setting up a report, calendar or pagination on a site. Either way there are numerous ways to do this but the following seems to be the quickest and most reliable method.

Function to split an php array into smaller chunk or section

function chunked_array($arrayToSplit, $noOfChunk) { 
   $myArray = array();
   $k = 0; 
   for ( $i=0;$i < count($arrayToSplit); $i++ ) {
      if ( !($i % $noOfChunk) ) { $k++; }
      $myArray[$k][] = $arrayToSplit[$i]; 
   } 
   return $myArray; 
}

Now let’s take an example of a to  z alphabets and divide them into 10 -10 array group.

$array = range('a','z'); // create an array from a to z
echo '<pre>'.print_r(chunked_array($array,10),true);

Following output we will get

Array
(
    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
            [6] => g
            [7] => h
            [8] => i
            [9] => j
        )

    [2] => Array
        (
            [0] => k
            [1] => l
            [2] => m
            [3] => n
            [4] => o
            [5] => p
            [6] => q
            [7] => r
            [8] => s
            [9] => t
        )

    [3] => Array
        (
            [0] => u
            [1] => v
            [2] => w
            [3] => x
            [4] => y
            [5] => z
        )

)

 

That’s It!

Thanks