![]() |
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: Table of Content Using array_chunk() functionThe 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:
Output: Array ( Using array_slice() functionThe 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:
Output: Array ( Approach 3: Using array_map with rangeYou 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.
Output Array ( [0] => Array ( [0] => G [1] => e [2] => e [3] => k ) [1] => Array ( [0] => s [1] => f ... Using a Generator FunctionIn 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:
Output Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) [1] => Array ( [0] => 5 [1] => 6 ... Using a While LoopThis 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.
Output Array ( [0] => Array ( [0] => G [1] => e [2] => e [3] => k ) [1] => Array ( [0] => s [1] => f ... Using array_map with rangeYou 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:
Output Array ( [0] => Array ( [0] => G [1] => e [2] => e [3] => k ) [1] => Array ( [0] => s [1] => f ... |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Related |
---|
![]() |
![]() |
|
|
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |