How to preserve the key when using array_chunk in PHP

Last Updated on

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

Introduction

This article shows how to preserve the key when using array_chunk in PHP. PHP array_chunk splits an array into chunks, and each chunk count equals the length argument of the function. There’s a detailed article on this function at FuelingPHP. This article also includes a brief review of the function before jumping to the main subject.

PHP array_chunk – A review

Here’s a review of this function with examples.

Function Signature

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

The array_chunk takes an array and length argument. The length indicates the size of each chunk. If the array cannot be evenly chunked, the last chunk count will be less than the length. There is an optional preserve_keys argument which by default is false. This argument is crucial in preserving keys when using this function in PHP.

Here’s an example of this function in PHP.

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

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
        )
 
)
*/

Preserve the key when using array_chunk in PHP

As already mentioned, the preserve_key argument helps retain the keys in chunks. The keys can be numeric or string. Here’s an example with string keys.

<?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
        )
 
)
*/
?>


Here’s another example with integer keys.

<?php
$index =
[
   101 => "Mark",
   222 => "Stacie",
   333 => "Tyson",
   444 => "Ron",
   512 => "Rosie",
   652 => "Bran",
   1012 => "Richard",
   1050 => "Kylie"
];
 
print_r(array_chunk($index,2, true));
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [101] => Mark
            [222] => Stacie
        )
 
    [1] => Array
        (
            [333] => Tyson
            [444] => Ron
        )
 
    [2] => Array
        (
            [512] => Rosie
            [652] => Bran
        )
 
    [3] => Array
        (
            [1012] => Richard
            [1050] => Kylie
        )
 
)
*/
?>

Voila! It is pretty easy. If you’ve made it up to here, we have something more related to this function.

How to reverse an array_chunk

So, the PHP array_merge could help reverse 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. 

Conclusion

So, this article answers how to preserve the key when using array_chunk in PHP. The function has the preserve_keys argument that can be set to true to preserve keys. Besides, the function also includes a bonus example of reversing an array_chunk. Hopefully, you’ve learned something new today. Stay tuned for more exciting and informative PHP content at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. 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.