How to Split Array into Specific Number of Chunks in PHP ?
Last Updated :
27 Sep, 2023
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:
Approach 1: 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
$arr = [
"G" , "e" , "e" , "k" , "s" ,
"f" , "o" , "r" , "G" , "e" ,
"e" , "k" , "s"
];
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
)
)
Approach 2: 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
$arr = [
"G" , "e" , "e" , "k" , "s" ,
"f" , "o" , "r" , "G" , "e" ,
"e" , "k" , "s"
];
$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
)
)
Share your thoughts in the comments
Please Login to comment...