• :
  • :

array_chunk: How to use with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

What is PHP array_chunk?

Description

PHP array_chunk function splits an array into chunks.

Function Signature

array_chunk(array $array, int $length, bool $preserve_keys = false): array

Arguments

  • $array – The input array
  • $length – The size of each chunk
  • $preserve_keys – Array keys will be preserved if it is true.

Return Types

This function returns a multidimensional array with a numeric index, each numeric index containing a chunk. 

Warnings/Errors

If the $length is less than 1, the function throws E_Warning and returns null.

Note

If the $array could not be partitioned into even chunks, the last chunk will have less than the $length number of elements.

Introduction – PHP array_chunk

PHP array_chunk function takes an array and splits it into chunks based on the $length argument. Each chunk has the $length count except for the last chunk which could have less than the $length number of elements if the array could not be partitioned evenly.

PHP array_chunk

The array_chunk PHP returns a multidimensional and numerically indexed array. Every index in this array contains a chunk. After this quick overview, let’s move on to see some examples.

Usage Example#1 – PHP array_chunk

Here’s an example of how to use array_chunk in PHP.

<?php
$arr = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
 
$chunks = array_chunk($arr, 2);
 
print_r($chunks);
?>

So, the array has ten values, and the $length specified is two. The resulting multidimensional array will have five values, and every value will be an array containing a chunk. Here’s the output.

/*
OUTPUT
Array
(
    [0] => Array
        (
            [0] => One
            [1] => Two
        )
 
    [1] => Array
        (
            [0] => Three
            [1] => Four
        )
 
    [2] => Array
        (
            [0] => Five
            [1] => Six
        )
 
    [3] => Array
        (
            [0] => Seven
            [1] => Eight
        )
 
    [4] => Array
        (
            [0] => Nine
            [1] => Ten
        )
 
)
*/

Usage Example#2 – PHP array_chunk

The array_chunk in PHP preserves keys if the $preserve_keys argument is set to true. Here’s how.

<?php
$arr = [
    'One' => 1,
    'Two' => 2,
    'Three' => 3,
    'Four' => 4,
    'Five' => 5,
    'Six' => 6
];
 
$chunks = array_chunk($arr, 2, true);
 
print_r($chunks);
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [One] => 1
            [Two] => 2
        )
 
    [1] => Array
        (
            [Three] => 3
            [Four] => 4
        )
 
    [2] => Array
        (
            [Five] => 5
            [Six] => 6
        )
 
)
*/
?>

Voila! That’s pretty much about the array_chunk PHP. But let’s go further ahead and see if there is a way to merge the chunks back.

How to reverse an array_chunk

So, the PHP array_merge could be helpful in reversing an array_chunk. Here’s how.

<?php
$arr = [
    'One' => 1,
    'Two' => 2,
    'Three' => 3,
    'Four' => 4,
    'Five' => 5,
    'Six' => 6
];
 
$chunks = array_chunk($arr, 2, true);
 
$reversed = array_merge(...$chunks);
 
print_r($reversed);
 
/*
OUTPUT
Array
(
    [One] => 1
    [Two] => 2
    [Three] => 3
    [Four] => 4
    [Five] => 5
    [Six] => 6
)
*/
?>

The spread operator … expands the array values. The array_merge function gets the chunks and merges them back into an array.

So, the array_chunk divides an array into chunks. Every chunk has $length count, with the last chunk being an exception. Another cool thing the array_chunk can do is laying a tabular structure. Let’s explore this idea in the next section.

The Calendar Month

So, talking about the tables, let’s assume an array with values ranging from 1 to 31, representing days of a calendar month. The image shows how these can be laid out in a tabular form.

The last row is an exception as it has three values while the other rows have seven values. This scenario is similar to the last chunk in an uneven array. So, the array_chunk can divide the days of a calendar just as the image shows. Here’s how.

<?php
 
$days = range(1, 31);
$rows = array_chunk($days, 7);
 
print "Days of a Month".PHP_EOL;
foreach ($rows as $row) {
    print PHP_EOL;
    foreach ($row as $value) {
        print $value.' ';
    }
    print PHP_EOL;
}
 
?>

Here’s the output.

/*
Days of a Month
 
1 2 3 4 5 6 7
 
8 9 10 11 12 13 14
 
15 16 17 18 19 20 21
 
22 23 24 25 26 27 28
 
29 30 31
*/

Awesome! An excellent example to end this article with.

Conclusion

This article explains the array_chunk in PHP with examples. In summary, the array_chunk divides an array into chunks of a specific count. Besides, the articles include an example to reverse the array_chunk partitions and an example of laying out a table using the array_chunk function. Hopefully, you have learned something new today. To learn more about PHP, stay tuned and keep an eye on the latest posts at FuelingPHP

Want to explore more PHP functions?

We have many fun articles related to PHP functions. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.