php Split an Array into N Arrays

时间:2021-01-18 21:41:03

I have an array of 18 values:

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');


I want to split this array into 9 different arrays so it should look like this:


array(
0 => array('a', 'b'),
1 => array('c', 'd'),
2 => array('e', 'f'),
3 => array('g', 'h'),
4 => array('i', 'j'),
5 => array('k', 'l'),
6 => array('m', 'n'),
7 => array('o', 'p'),
8 => array('q', 'r')
)


Solution:

function array_split($array, $parts) {
      return array_chunk($array, ceil(count($array) / $parts));
}

$result = array_split($array, 9);