PHP array_chunk(): Split Arrays into Manageable Parts

When working with big arrays in PHP, things can get messy. That is where php array_chunk() steps in by providing a way to get those big arrays broken down into small, manageable pieces, from organizing data that is to be displayed to splitting content into rows or handling large datasets cleanly and efficiently using array_chunk().

In this article, you will learn what the PHP function array_chunk() does and how to use it, along with practical examples, and why it’s a convenient tool in the hands of any PHP developer.

What is php array_chunk()?

In other words, the array_chunk() in PHP is a function that takes one array and breaks it into smaller arrays or, in other words, chunks: take a whole long list of items and divide it into portions that are easier to handle or manage.

Be it displaying products across rows, creating groups, or processing large sets of data, array_chunk() will do what is required.

Syntax of PHP array_chunk()

Accordingly, the syntax is relatively simple; there are only a couple of main options:

array_chunk(array $array, int $size, bool $preserve_keys = false): array
  • $array: This is the source array that you would want to split up.
  • $size: Size that the chunks should contain.
  • $preserve_keys (optional): Whether to preserve the original keys of the array. If TRUE, PHP will keep the keys intact.

The next section explains how array_chunk() works with a simple example.

Basic Example of php array_chunk()

Suppose you have an array of students and you want to divide them into groups of three. Here is how array_chunk() does just that for you in PHP:

$students = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
$groups = array_chunk($students, 3);

print_r($groups);

Here is the output:

Array
(
    [0] => Array ( [0] => Alice [1] => Bob [2] => Charlie )
    [1] => Array ( [0] => Dave [1] => Eve [2] => Frank )
)

Above, array_chunk() divided our $students array into two smaller arrays of three each. It’s a clean and clear-cut way to handle grouping without any excess loops or conditions.

Now, in the next section, we will see how the preserve_keys parameter works and when you might need it.

Using preserve_keys with the array_chunk()

By default, array_chunk() will reset the keys to begin at 0 for each chunk. But what if you needed to retain the original keys, say you are dealing with associative arrays? Well, that’s where preserve_keys comes in. Here it is in action:

$student_scores = ["Alice" => 95, "Bob" => 87, "Charlie" => 92, "Dave" => 88];
$groups = array_chunk($student_scores, 2, true);

print_r($groups);

Here is the output:

Array
(
    [0] => Array ( [Alice] => 95 [Bob] => 87 )
    [1] => Array ( [Charlie] => 92 [Dave] => 88 )
)

This will work, but setting preserve_keys to true, the original names are kept as keys for readability and ease of use. If preserve_keys was not set, this function would reset the keys in each chunk.

Wrapping Up

This array_chunk() function in PHP is powerful yet simple in terms of splitting an array into parts. Ideally, it’s great for creating manageable chunks in items being displayed in rows, handling large datasets, and batch grouping of data.

Once you get accustomed to the syntax, optional parameters, and use, you’ll commit it smoothly to your PHP projects. Just keep in mind how chunk size and key preservation affect the handling of your data, and you will squeeze the most from array_chunk().

Similar Reads

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

PHP Functions: The Complete Guide for Beginners

So, what is a function? Quite simply, a function in PHP is a set of instructions you write once, and…

PHP array_diff_key Function: How it Works with Examples

PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

PHP Access Modifiers: How Public, Private & Protected Work

PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the…

PHP sizeof: How to Count Elements in Arrays with Examples

The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

How to Insert Multiple Rows in MySQL with PHP?

Inserting multiple data rows using PHP is a basic task. However when you start working with MySQL databases, So that…

PHP Float: Understanding Float Precision in PHP

A PHP float is a kind of number that has a decimal point, like 2.45 or 0.11. It’s also called…

PHP continue Statement: How to Skip Steps in Iteration

The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…

PHP array_combine: How to Merge Arrays as Key and Value

The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…

PHP foreach Loop: How to Access Keys & Values in Arrays

PHP foreach loop came to help work with array data in a simple way. Arrays and objects grew more common…

Previous Article

PHP array_pop: Remove and Return the Last Element of an Array

Next Article

PHP $GLOBALS: Access Global Variables with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.