0
0
PHPprogramming~5 mins

Array chunk and pad in PHP

Choose your learning style9 modes available
Introduction

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.

When you want to show items in groups, like pages of products on a website.
When you need to process data in small pieces instead of all at once.
When you want to fill missing spots in a list to keep the size consistent.
When preparing data for tables where each row must have the same number of columns.
Syntax
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.

Examples
Splits the array into chunks of 2 elements each.
PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$chunks = array_chunk($numbers, 2);
print_r($chunks);
?>
Chunking an empty array returns an empty array.
PHP
<?php
$empty = [];
$chunks = array_chunk($empty, 3);
print_r($chunks);
?>
Chunking a single-element array with size 2 returns one chunk with that element.
PHP
<?php
$single = [10];
$chunks = array_chunk($single, 2);
print_r($chunks);
?>
Pads the array to size 5 by adding zeros at the end.
PHP
<?php
$values = [1, 2];
$padded = array_pad($values, 5, 0);
print_r($padded);
?>
Sample Program

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
<?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]);
?>
OutputSuccess
Important Notes

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.

Summary

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.