Home > Back-end >  Split an array into an equal chunks and keep big chunk last
Split an array into an equal chunks and keep big chunk last

Time:10-22

I have an odd array of 7 elements contains some values :

$languages = ['php', 'mysql', 'java', 'nodejs', 'ruby', 'go', 'c#'];

I would like to split the array into equal chunks, and keep the big chunk last for example I would like to have an output like:

[
  ['php', 'mysql'],
  ['java', 'nodejs'],
  ['ruby', 'go', 'c#']  // big chunk last as you can see
]

I tried to use array_chunk function :

return array_chunk($languages, 2);

but I got

 [
  ['php', 'mysql'],
  ['java', 'nodejs'],
  ['ruby', 'go'],
  ['c#']
]

CodePudding user response:

Check if the last chunk is undersized, and if so merge it into the previous.

function special_chunk($array, $size) {
    $chunks = array_chunk($array, 2);
    $count = count($chunks);
    
    if( count($chunks[$count-1]) < $size ) {
        $chunks[$count-2] = array_merge($chunks[$count-2], $chunks[$count-1]);
        unset($chunks[$count-1]);
    }
    return $chunks;
}

$languages = ['php', 'mysql', 'java', 'nodejs', 'ruby', 'go', 'c#'];

var_dump(
    special_chunk($languages, 2)
);

Output:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "php"
    [1]=>
    string(5) "mysql"
  }
  [1]=>
  array(2) {
    [0]=>
    string(4) "java"
    [1]=>
    string(6) "nodejs"
  }
  [2]=>
  array(3) {
    [0]=>
    string(4) "ruby"
    [1]=>
    string(2) "go"
    [2]=>
    string(2) "c#"
  }
}
  •  Tags:  
  • php
  • Related