Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

How to split an array into multiple small sub-arrays in PHP

1 Answer

0 votes
function splitArray($arr, $chunk) {
    $result = [];
    $size = count($arr);
    
    for ($i = 0; $i < $size; $i += $chunk) {
        $result[] = array_slice($arr, $i, $chunk);
    }
    
    return $result;
}

$arr = range(1, 26);

print_r(splitArray($arr, 4));



/*
run:

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

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

    [2] => Array
        (
            [0] => 9
            [1] => 10
            [2] => 11
            [3] => 12
        )

    [3] => Array
        (
            [0] => 13
            [1] => 14
            [2] => 15
            [3] => 16
        )

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

    [5] => Array
        (
            [0] => 21
            [1] => 22
            [2] => 23
            [3] => 24
        )

    [6] => Array
        (
            [0] => 25
            [1] => 26
        )

)

*/

 



answered Nov 12, 2024 by avibootz
edited Nov 12, 2024 by avibootz

Related questions

...