Professor Zoom Professor Zoom - 7 months ago 32
PHP Question

How to limit an array and split it into more arrays? PHP

I would like to do this...

I got this array with 50 elements

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50);


and I would like to add the first 20 elements into another array, 20 should be the limit, if it is greater than 20 add the next 20 into another array and do this operation to only get array with 20 elements

I tried with this

$number = count($data);
$pieces = array_chunk($data, ceil($number / 2));


And I get only two sub-arrays from that, I'm lost, I need some ideas about how to achieve this, thanks.

Answer

That's because you're only trying to get 2 subarrays, since you're taking the total number and dividing it by 2. You're on the right track, you just need to specify the number of elements you want in each subarray:

$pieces = array_chunk($data, 20);