PHP array_chunk() function is “used to split an array into parts or chunks of new arrays“. The size of each chunk is determined by the size parameter that you pass to the function.
The last chunk may contain fewer elements than the specified size.
Syntax
array_chunk($array,size,preserve_key);
Parameters
$array: The parameter is required, which specifies an array to split.
size: The parameter is required; an integer size of each chunk.
preserve_key: It is an optional parameter. Two possible values.
- true – Preserves the keys.
- false – Default. Reindexes the chunk numerically.
Visual Representation
Example 1: How to Use PHP array_chunk() function
<?php
$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO', 'Suits'];
$netflix_chunk = array_chunk($netflix,2);
print_r($netflix_chunk);
Output
Array
(
[0] => Array
(
[0] => Stranger Things
[1] => Black Mirror
)
[1] => Array
(
[0] => Bright
[1] => XOXO
)
[2] => Array
(
[0] => Suits
)
)
Example 2: Preserve the original keys
<?php
$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO', 'Suits'];
$netflix_chunk = array_chunk($netflix,2, true);
print_r($netflix_chunk);
Output
Array
(
[0] => Array
(
[0] => Stranger Things
[1] => Black Mirror
)
[1] => Array
(
[2] => Bright
[3] => XOXO
)
[2] => Array
(
[4] => Suits
)
)
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
great article. you explained very well