Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a multi dimensional array every 3 elements

Tags:

loops

foreach

php

I have the following array:

Array {
    [0] => text1
    [1] => text2
    [3] => text3
    [4] => text4
    ...
    [200] => text200
}

How can I create a foreach loop that will divide the above array to create a sub array for every 3 elements?

Array {
    [0] => Array {
                [0] => text1
                [1] => text2
                [2] => text3 
    }
    [1] => Array {
                [0] => text4
                [1] => text5
                [2] => text6
    }   
   ......
}
like image 880
Or Weinberger Avatar asked Feb 23 '26 08:02

Or Weinberger


1 Answers

you can use a build in function , array_chunk()

array_chunk($input_array, 3)
like image 102
Haim Evgi Avatar answered Feb 24 '26 20:02

Haim Evgi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!