We use array chunk and pad to split a big list into smaller parts and make sure each part has the same size by adding extra values if needed.
Array chunk and pad in PHP
<?php // Array chunk $chunks = array_chunk(array $array, int $size, bool $preserve_keys = false); // Array pad $padded_array = array_pad(array $array, int $size, mixed $value); ?>
array_chunk splits an array into smaller arrays of a given size.
array_pad adds extra values to an array until it reaches the desired size.
<?php $numbers = [1, 2, 3, 4, 5]; $chunks = array_chunk($numbers, 2); print_r($chunks); ?>
<?php $empty = []; $chunks = array_chunk($empty, 3); print_r($chunks); ?>
<?php $single = [10]; $chunks = array_chunk($single, 2); print_r($chunks); ?>
<?php $values = [1, 2]; $padded = array_pad($values, 5, 0); print_r($padded); ?>
This program shows how to split an array into chunks of 2 items and then pad the last chunk to have exactly 3 items by adding the word 'empty'.
<?php // Original array $fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; // Show original array echo "Original array:\n"; print_r($fruits); // Split into chunks of 2 $fruit_chunks = array_chunk($fruits, 2); echo "\nArray chunks (size 2):\n"; print_r($fruit_chunks); // Pad the last chunk to size 3 with 'empty' $last_chunk_index = count($fruit_chunks) - 1; $fruit_chunks[$last_chunk_index] = array_pad($fruit_chunks[$last_chunk_index], 3, 'empty'); echo "\nLast chunk after padding to size 3:\n"; print_r($fruit_chunks[$last_chunk_index]); ?>
Time complexity: array_chunk runs in O(n) where n is the number of elements; array_pad also runs in O(m) where m is the padding size.
Space complexity: Both create new arrays, so space grows with the size of the input and output.
A common mistake is forgetting that array_chunk returns a new array of arrays, not modifying the original.
Use array_chunk when you want to split data into parts; use array_pad when you want to fill missing spots to keep size consistent.
array_chunk splits an array into smaller arrays of a fixed size.
array_pad adds extra values to an array to reach a desired size.
These functions help organize and prepare data for display or processing in equal-sized groups.