Jump to: navigation, search

Php array chunk

From w3cyberlearnings

Contents

PHP function array_chunk

This function splits an array into chunks for a new array

Syntax array_chunk

  • array: array input
  • size: size to split
  • preserve_key: true (preserve the key as the origional array), false (default, not reserve)
array_chunk(array, size, preserve_key);

Example 1

<?php

$person = array('John', 'Marry', 'Bob', 'Lucous', 'Chris', 'Paul');

print_r(array_chunk($person, 2));
?>

Output

Array
(
    [0] => Array
        (
            [0] => John
            [1] => Marry
        )

    [1] => Array
        (
            [0] => Bob
            [1] => Lucous
        )

    [2] => Array
        (
            [0] => Chris
            [1] => Paul
        )

)


Example 2: Preserve key

<?php

$person = array('John'=>30, 'Marry'=>80, 'Bob'=>80, 'Lucous'=>30, 'Chris'=>29, 'Paul'=>93);

print_r(array_chunk($person, 2,true));
?>

Output

Array
(
    [0] => Array
        (
            [John] => 30
            [Marry] => 80
        )

    [1] => Array
        (
            [Bob] => 80
            [Lucous] => 30
        )

    [2] => Array
        (
            [Chris] => 29
            [Paul] => 93
        )

)

Example 3

<?php

$person = array('John'=>30, 'Marry'=>80, 'Bob'=>80, 'Lucous'=>30, 'Chris'=>29, 'Paul'=>93);

print_r(array_chunk($person, 2));
?>

Output

Array
(
    [0] => Array
        (
            [0] => 30
            [1] => 80
        )

    [1] => Array
        (
            [0] => 80
            [1] => 30
        )

    [2] => Array
        (
            [0] => 29
            [1] => 93
        )

)

Related Links


Navigation
Web
SQL
MISC
References