How to usearray_map with range in PHP

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);

?>

Output
Array
(
    [0] => Array
        (
            [0] => G
            [1] => e
            [2] => e
            [3] => k
        )

    [1] => Array
        (
            [0] => s
            [1] => f
 ...




How to Split Array into Specific Number of Chunks in PHP ?

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() function
  • Using array_slice() function
  • Using array_map with range

Similar Reads

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....

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....

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....