array_chunk

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

array_chunkSplittet ein Array in Teile auf

Beschreibung

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

array_chunk() teilt das Array in Arrays mit length Elementen auf. Das letzte Array kann weniger als length Werte enthalten.

Parameter-Liste

array

Das Eingabe-Array

length

Die Größe der einzelnen Teile

preserve_keys

Falls auf true gesetzt, bleiben die Schlüssel erhalten. Der Standard ist false, wodurch jeder Teil neue numerische Indizes erhält.

Rückgabewerte

Gibt ein mehrdimensionales Array zurück, das beginnend mit Null jeweils length Elemente enthält.

Fehler/Exceptions

Wenn length kleiner ist als 1, wird ein ValueError ausgelöst.

Changelog

Version Beschreibung
8.0.0 Wenn length kleiner ist als 1, wird nun ein ValueError ausgelöst; vorher wurde ein Fehler der Stufe E_WARNING ausgelöst, und die Funktion gab null zurück.

Beispiele

Beispiel #1 array_chunk()-Beispiel

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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
        )

)

Siehe auch

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]
    */
?>