Home > Software engineering >  Combination of 4 Elements from Array
Combination of 4 Elements from Array

Time:02-17

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

I want output like

['1, 2, 3, 4', '5, 6, 7, 8', '9'];

Can someone please help me with this? Please... I need logic for this. I tried many ways but failed.

CodePudding user response:

You can use array_chunk() to split your array into chunks of 4 items. Then array_map() to implode() each chunk:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunk = array_chunk($array, 4);
var_dump(array_map(fn($item) => implode(',', $item), $chunk));

Outputs:

array(3) {
  [0]=> string(7) "1,2,3,4"
  [1]=> string(7) "5,6,7,8"
  [2]=> string(1) "9"
}

CodePudding user response:

you can do that

const $array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const $chunk = $array.reduce((r,v,i)=>
  {
  if (!(i%4))  r.pos         = r.resp.push(`${v}`) -1
  else         r.resp[r.pos]  = `,${v}`
  return r
  }, { resp : [], pos:0 } ).resp


console.log( $chunk )

  • Related