array_chunk

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

array_chunkSplit an array into chunks

Опис

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

Chunks an array into arrays with length elements. The last chunk may contain less than length elements.

Параметри

array

The array to work on

length

The size of each chunk

preserve_keys

When set to true keys will be preserved. Default is false which will reindex the chunk numerically

Значення, що повертаються

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing length elements.

Помилки/виключення

If length is less than 1, a ValueError will be thrown.

Журнал змін

Версія Опис
8.0.0 If length is less than 1, a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned null.

Приклади

Приклад #1 array_chunk() example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Поданий вище приклад виведе:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

Прогляньте також

add a note

User Contributed Notes 18 notes

up
71
azspot at gmail dot com
19 years ago
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.

So, here is the output of my own dabbling on the matter:

<?php

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$citylist = array( "Black Canyon City", "Chandler", "Flagstaff", "Gilbert", "Glendale", "Globe", "Mesa", "Miami",
                   "Phoenix", "Peoria", "Prescott", "Scottsdale", "Sun City", "Surprise", "Tempe", "Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );

?>

Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
up
27
Andrew Martin
8 years ago
To reverse an array_chunk, use array_merge, passing the chunks as a variadic:

<?php
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

$chunks = array_chunk($array, 3);
// $chunks = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

$de_chunked = array_merge(…$chunks);
// $de_chunked = [1, 2, 3, 4, 5, 6, 7, 8, 9]
?>
up
19
nate at ruggfamily dot com
16 years ago
If you just want to grab one chunk from an array, you should use array_slice().
up
21
Anonymous
20 years ago
Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :

<?php
    function array_chunk_vertical($data, $columns) {
        $n = count($data) ;
        $per_column = floor($n / $columns) ;
        $rest = $n % $columns ;

        // The map
        $per_columns = array( ) ;
        for ( $i = 0 ; $i < $columns ; $i++ ) {
            $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
        }

        $tabular = array( ) ;
        foreach ( $per_columns as $rows ) {
            for ( $i = 0 ; $i < $rows ; $i++ ) {
                $tabular[$i][ ] = array_shift($data) ;
            }
        }

        return $tabular ;
    }

    header('Content-Type: text/plain') ;

    $data = array_chunk_vertical(range(1, 31), 7) ;
    foreach ( $data as $row ) {
        foreach ( $row as $value ) {
            printf('[%2s]', $value) ;
        }
        echo "\r\n" ;
    }

    /*
        Output :

        [ 1][ 6][11][16][20][24][28]
        [ 2][ 7][12][17][21][25][29]
        [ 3][ 8][13][18][22][26][30]
        [ 4][ 9][14][19][23][27][31]
        [ 5][10][15]
    */
?>
up
5
dustin at fivetechnology dot com
10 years ago
Had need to chunk an object which implemented ArrayAccess Iterator Countable.  array_chunk wouldn't do it.  Should work for any list of things

<?php
   $listOfThings = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
   print_r(chunk_iterable($listOfThings, 4);

  function chunk_iterable($listOfThings, $size) {
      $chunk = 0;
      $chunks = array_fill(0, ceil(count($listOfThings) / $size) - 1, array());
      $index = 0;
      foreach($listOfThings as $thing) {
        if ($index && $index % $size == 0) $chunk++;
        $chunks[$chunk][] = $thing;
        $index++;
      }
      return $chunks;
  }
?>
up
7
Anonymous
5 years ago
Most easy way split array to parts

<?php

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

print_r(array_chunk($arr, ceil(count($arr) / 2)));
// return: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

print_r(array_chunk($arr, ceil(count($arr) / 3)));
// return: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

?>
up
17
OIS
18 years ago
Response to azspot at gmail dot com function partition.

$columns = 3;
$citylist = array('Black Canyon City', 'Chandler', 'Flagstaff', 'Gilbert', 'Glendale', 'Globe', 'Mesa', 'Miami', 'Phoenix', 'Peoria', 'Prescott', 'Scottsdale', 'Sun City', 'Surprise', 'Tempe', 'Tucson', 'Wickenburg');
print_r(array_chunk($citylist, ceil(count($citylist) / $columns)));

Output:
Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
up
13
phpm at nreynolds dot me dot uk
21 years ago
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7 
8 9 10 11 12 13 14 
15 16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31 
2 7  12 17 22 27 
3 8  13 18 23 28 
4 9  14 19 24 29 
5 10 15 20 25 30 

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29 
2 9  16 23 30 
3 10 17 24 31 
4 11 18 25 
5 12 19 26 
6 13 20 27 
7 14 21 28 

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();
    
    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }
    
    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }
        
        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }
    
    return $chunks;
}

?>
up
6
suisuiruyi at aliyun dot com
10 years ago
chunk array vertically

$arr    = range(1, 19);
function array_chunk_vertical($arr, $percolnum){
    $n = count($arr);
    $mod    = $n % $percolnum;
    $cols   = floor($n / $percolnum);
    $mod ? $cols++ : null ;
    $re     = array();
    for($col = 0; $col < $cols; $col++){
        for($row = 0; $row < $percolnum; $row++){
            if($arr){
                $re[$row][]   = array_shift($arr);
            }
        }
    }
    return $re;
}
$result = array_chunk_vertical($arr, 6);
foreach($result  as $row){
    foreach($row as $val){
        echo '['.$val.']';
    }
    echo '<br/>';
}
/*
[1][7][13][19]
[2][8][14]
[3][9][15]
[4][10][16]
[5][11][17]
[6][12][18]
 */
up
6
mick at vandermostvanspijk dot nl
22 years ago
[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]

For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:

<?php
if (!function_exists('array_chunk')) {
    function array_chunk( $input, $size, $preserve_keys = false) {
        @reset( $input );
        
        $i = $j = 0;

        while( @list( $key, $value ) = @each( $input ) ) {
            if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
            }

            if( count( $chunks[$i] ) < $size ) {
                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $chunks[$i][] = $value;
                }
            } else {
                $i++;

                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $j = 0;
                    $chunks[$i][$j] = $value;
                }
            }
        }

        return $chunks