How to Split Array into Specific Number of Chunks in PHP ?
Last Updated :
03 Jul, 2024
This article will show you how to split an array into a specific number of chunks using PHP. There are basically two approaches to solve this problem, these are:
Using array_chunk() function
The array_chunk() function is used to split an array into parts or chunks of a given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk.
Syntax:
array array_chunk( $array, $size, $preserve_keys )
Example:
PHP
<?php
// PHP Program to Split Array into
// Specific Number of Chunks
// Declare an array
$arr = [
"G", "e", "e", "k", "s",
"f", "o", "r", "G", "e",
"e", "k", "s"
];
// Use array_chunk() function to
// split array into chunks
print_r(array_chunk($arr, 4));
?>
Output:
Array (
[0] => Array (
[0] => G
[1] => e
[2] => e
[3] => k
)
[1] => Array (
[0] => s
[1] => f
[2] => o
[3] => r
)
[2] => Array (
[0] => G
[1] => e
[2] => e
[3] => k
)
[3] => Array (
[0] => s
)
)
Using array_slice() function
The array_slice() function is used to fetch a part of an array by slicing through it, according to the users choice.
Syntax:
array_slice($array, $start_point, $slicing_range, preserve)
Example:
PHP
<?php
// PHP Program to split array into
// Specific Number of Chunks
// Declare an array
$arr = [
"G", "e", "e", "k", "s",
"f", "o", "r", "G", "e",
"e", "k", "s"
];
// Use array_slice() function to
// split array into chunks
$splitArr = [
array_slice($arr, 0, 4),
array_slice($arr, 4, 7),
array_slice($arr, 8, 12),
array_slice($arr, 12, 1),
];
print_r($splitArr);
?>
Output:
Array (
[0] => Array (
[0] => G
[1] => e
[2] => e
[3] => k
)
[1] => Array (
[0] => s
[1] => f
[2] => o
[3] => r
)
[2] => Array (
[0] => G
[1] => e
[2] => e
[3] => k
)
[3] => Array (
[0] => s
)
)
Approach 3: Using array_map with range
You can use array_map with range to generate chunk indexes based on the array size and chunk size. Then, apply array_slice to extract chunks using these indexes, resulting in the array split into specific-sized chunks.
Example: This PHP script defines a custom_array_chunk function to split an array $arr into chunks of size 4 using array_map, range, and array_slice, displaying the result with print_r.
PHP
<?php
// Custom function to split array into chunks
function custom_array_chunk($array, $chunk_size) {
// Calculate the number of chunks needed
$num_chunks = ceil(count($array) / $chunk_size);
// Use array_map with range to create chunks
return array_map(function($i) use ($array, $chunk_size) {
// Calculate start index of current chunk
$start = $i * $chunk_size;
// Return slice of array for current chunk
return array_slice($array, $start, $chunk_size);
}, range(0, $num_chunks - 1));
}
// Declare an array
$arr = [
"G", "e", "e", "k", "s",
"f", "o", "r", "G", "e",
"e", "k", "s"
];
// Split array into chunks of size 4 using custom function
$result = custom_array_chunk($arr, 4);
// Print the result
print_r($result);
?>
OutputArray
(
[0] => Array
(
[0] => G
[1] => e
[2] => e
[3] => k
)
[1] => Array
(
[0] => s
[1] => f
...
Using a Generator Function
In the generator function approach, define a generator that yields chunks of the original array. Calculate the chunk size based on the desired number of chunks, then use array_slice() within the generator. Convert the generator’s output to an array using iterator_to_array().
Example:
PHP
<?php
function array_chunk_generator($array, $numberOfChunks) {
$chunkSize = ceil(count($array) / $numberOfChunks);
for ($i = 0; $i < $numberOfChunks; $i++) {
yield array_slice($array, $i * $chunkSize, $chunkSize);
}
}
$array = range(1, 10);
$numberOfChunks = 3;
$chunks = iterator_to_array(array_chunk_generator($array, $numberOfChunks));
print_r($chunks);
?>
OutputArray
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
...
Using a While Loop
This method involves calculating the chunk size based on the desired number of chunks and using a while loop to slice the array into these chunks.
Example: In this example, the splitArrayIntoChunks function first calculates the chunk size by dividing the total number of elements by the number of desired chunks and rounding up using ceil. It then initializes an empty array for the chunks and an index variable. The while loop iterates through the array, slicing off chunks of the calculated size and adding them to the chunks array until the entire array has been processed.
PHP
<?php
function splitArrayIntoChunks($array, $numChunks) {
$chunkSize = ceil(count($array) / $numChunks);
$chunks = [];
$index = 0;
while ($index < count($array)) {
$chunks[] = array_slice($array, $index, $chunkSize);
$index += $chunkSize;
}
return $chunks;
}
// Example usage
$array = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'];
$numChunks = 4;
$chunks = splitArrayIntoChunks($array, $numChunks);
print_r($chunks);
?>
OutputArray
(
[0] => Array
(
[0] => G
[1] => e
[2] => e
[3] => k
)
[1] => Array
(
[0] => s
[1] => f
...
Using array_map with range
You can use array_map with range to generate chunk indexes based on the array size and chunk size. Then, apply array_slice to extract chunks using these indexes, resulting in the array split into specific-sized chunks.
Example:
PHP
<?php
function custom_array_chunk($array, $size) {
return array_map(function($i) use ($array, $size) {
return array_slice($array, $i * $size, $size);
}, range(0, ceil(count($array) / $size) - 1));
}
// Example usage:
$array = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'];
$chunked_array = custom_array_chunk($array, 4);
print_r($chunked_array);
?>
OutputArray
(
[0] => Array
(
[0] => G
[1] => e
[2] => e
[3] => k
)
[1] => Array
(
[0] => s
[1] => f
...
Similar Reads
How to put string in array, split by new line in PHP ?
Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are splitted by the newline.Example: Input : string is 'Ankit \n Ram \n Shyam' Output : Array ( [0] => Ankit [1] => Ram [2] => Shyam ) Using explode() Fu
2 min read
How to Count of Repeating Digits in a Given Number in PHP ?
Counting the number of repeating digits in a given number is a common task in programming. This can be useful in various scenarios, such as data analysis or validation. In this article, we will explore different approaches to counting the repeating digits in a given number using PHP. Table of Conten
5 min read
How to Convert Seconds into Hours and Minutes in PHP ?
Given a number n (time in seconds), the task is to convert the given number of seconds into hours and minutes in PHP. Examples: Input: 3691215Output: 1025 hours and 20 minutesInput: 1296Output: 0 hours and 21 minutesIn PHP, you can convert a duration in seconds into hours and minutes using basic ari
1 min read
How to Get first N number of Elements From an Array in PHP?
Given an array, the task is to get the first N number of elements from the array in PHP. There are various approaches to achieve this task. In this article, we will explore all approaches with detailed explanations. These are the following approaches: Table of Content Using array_slice() FunctionUsi
3 min read
How to Find the Missing Number in a Given Integer Array of 1 to 100 in PHP?
Finding the missing number in an integer array ranging from 1 to 100 is a common algorithmic problem. In PHP, this can be efficiently achieved by leveraging the arithmetic properties of the series. The sum of numbers from 1 to 100 is known, and by comparing this expected sum with the actual sum of t
3 min read
Split a String into an Array of Words in PHP
In PHP, splitting a string into an array involves breaking a string into smaller parts based on a delimiter or a pattern and storing those parts as elements of an array. PHP provides several methods to achieve this, making it easy to convert a string into an array of words: Table of Content Using ex
3 min read
How to Convert Array to String in PHP?
We are given an array and the task is to convert the array elements into a string. Below are the approaches to convert an array to a string in PHP: Table of Content Using implode() functionUsing json_encode() FunctionUsing sprintfUsing serialize() FunctionUsing implode() functionThe implode() method
2 min read
How to merge arrays and preserve the keys in PHP ?
Arrays in PHP are created using array() function. Arrays are variable that can hold more than one values at a time. There are three types of arrays: Indexed Arrays Associative Arrays Multidimensional Arrays Each and every value in an array has a name or identity attached to it used to access that el
2 min read
How to Create an Array of Given Size in PHP?
This article will show you how to create an array of given size in PHP. PHP arrays are versatile data structures that can hold multiple values. Sometimes, it's necessary to create an array of a specific size, either filled with default values or left empty. Table of Content Using array_fill() Functi
3 min read
How to calculate total time of an array in PHP ?
Given an array containing the time in hr:min:sec format. The task is to calculate the total time. If the total time is greater then 24 hours then the total time will not start with 0. It will display the total time. There are two ways to calculate the total time from the array. Using strtotime() fun
2 min read