Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array_chunk
php
array
communitycreator

What is the array_chunk method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The array_chunk method is used to split an array into multiple arrays of a specific length.

Syntax


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

Arguments

  • array: The array to be split.

  • length: The number of elements in each split array. The last split array may contain fewer elements than length.

  • preserve_keys: A Boolean value. When set to true, the array’s keys while splitting are maintained. Otherwise, for each chunk of the array, a numeric reindex will happen.

Return type

This method returns a multidimensional array as a result. The returned array is numerically indexed from 0.

Code

<?php
$input_array = array(
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5
);
echo "Chunk array into length - 2, without preserving keys";
print_r(array_chunk($input_array, 2));
echo "Chunk array into length - 3, with preserving keys";
print_r(array_chunk($input_array, 3, true));
?>

Explanation

In the code above, we split the array into different lengths with and without preserving keys of the array, using the array_chunk method.

RELATED TAGS

array_chunk
php
array
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring