PHP array_chunk() Function

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.

  1. true – Preserves the keys.
  2. false – Default. Reindexes the chunk numerically.

Visual RepresentationVisual Representation of PHP array_chunk() Function

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 keysVisual Representation of 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.

1 thought on “PHP array_chunk() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.