update page now

Voting

: zero plus zero?
(Example: nine)

The Note You're Voting On

php at andryk dot moe
11 days ago
another function of array_chunk, make N chunks divided in equal parts

<?php
function array_chunk_ep(array $array, int $num, $preserve_keys = false)
{
    $ac = count($array);

    $asl = (int) ($ac / $num);
    $arexc = $ac - $asl * $num;
    $offset = 0;

    $result = [];

    for ($i = 0; $i < $num; $i++)
    {
        $length = $asl + ((0 < $arexc--) ? 1 : 0);
        $result[] = array_slice($array, $offset, $length, $preserve_keys);
        $offset += $length;
    }

    return $result;
}

print_r(array_chunk_ep(range(0, 23), 5));

/*
Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

    [1] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 7
            [3] => 8
            [4] => 9
        )

    [2] => Array
        (
            [0] => 10
            [1] => 11
            [2] => 12
            [3] => 13
            [4] => 14
        )

    [3] => Array
        (
            [0] => 15
            [1] => 16
            [2] => 17
            [3] => 18
            [4] => 19
        )

    [4] => Array
        (
            [0] => 20
            [1] => 21
            [2] => 22
            [3] => 23
        )
)
*/

print_r(array_chunk_ep([1 => 'a', 3 => 'b', 5 => 'c', 7 => 'd',], 3, true));

/*
Array
(
    [0] => Array
        (
            [1] => a
            [3] => b
        )

    [1] => Array
        (
            [5] => c
        )

    [2] => Array
        (
            [7] => d
        )
)
*/
?>

<< Back to user notes page

To Top