Array chunk example with PHP
Posted by : Darko Borojevic - contact me
Array chunk algorithm with PHPThis example can show You how to think about dividing bigger Arrays into smaller units, for the purpose of let's say, building a custom pagination. Here, we have built a custom function, fairly simple one, that takes an array of numbers as an input (and yes, I'm using PHP-7 type hints here), and constructs rows based on the second parameter which is a number of columns wanted.
Code exampleThis type of algorithms can be useful in building helper functions for constructing widgets, paginations, tag clouds etc., but the important lesson is to use this type of thinking in different code repeating situations where different array php functions can be utilized along with loops to automate well formated data rendering.
We can also use PHP's array_chunk() function to split an array in chunks of certain size, depending upon the parameters that are passed to the function. First parameter has to be an array, and the second parameter is an integer that determines how many chunks will be applied. This function returns a multidimensional numerically indexed array, with each dimension containing
array_chunk() function usage for similar tasks
sizeelements starting at 0. The last chunk may contain less elements than desired size of the chunk. If the second parameter is equal or larger than the original array size, the function returns the original array. If size is less than 1, E_WARNING will be thrown. The
$preserve_keysparameter takes Boolean value, and if this argument is set to TRUE then the keys are preserved, otherwise the chunk is reindexed starting from 0.
Array exampleNow we apply array_chunk() with true flag as the third parameter:
Array_chunk() with true flag parameterNow we get
$fooddelivered as two sub arrays, but with the same original keys preserved, as seen below. This functionality can be useful in real life scenarios, where for example, we have a large array, but now we would like to chunk that array but in a way that we group certain parts of that array together, and preserving the original keys in the process.