PHP Formatter

A Unique Blog about PHP

Array Chunk Function

The array_chunk() function on the on the other hand as the name implies, divides an array into chunks or several tables from the source table. The syntax goes something like array_chunk(array,size,preserve_key), wherein the array is the table that would be divided, the size is the number of elements which the new arrays are to contain and the preserve key which can either be true or false is used to either retain or revise the key or pointer value of the original table. An example is shown below:

$a=array(�a�=>�Cat�, �b�=>�Dog�, �c�=>�Horse�,�d�=>�Cow�); print_r(array_chunk($a,2); ?>

The code would have an output of:

Array ( [0] => Array ( [0] = > Cat [1] => Dog ) [1] => Array ( [0] => Horse [1] => Cow ) )

As we can see, the original array has been divided into two arrays array0 and array1 and a value that is not given for the key had it assigned a new key for each of the tables. Another example would be :

$a=array(�a�=>�Cat�, �b�=>�Dog�, �c�=>�Horse�,�d�=>�Cow�); print_r(array_chunk($a,2,true); ?>

This would then give us ;

Array ( [0] => Array ( [a] = > Cat [b] => Dog ) [1] => Array ( [c] => Horse [d] => Cow ) )

This shows the significance of the retain key field wherein the two new arrays retained their original keys. The reverse of which would be the array_combine() which divided the array into one which holds the keys and one with the values.