0

What is the best way to convert array like:

array(1,2,3,4,5,6,7,8,9,10)

to:

  array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9),
    array(10),
  );

I came up with something like:

$flat = array(1,2,3,4,5,6,7,8,9,10);
$colsLimit = 3;
$offset = 0;
$multi = array();

while($sliced = array_slice($flat, $offset, $colsLimit)) {
  $multi[] = $sliced;
  $offset += 3;
}

A better solutions are welcome.

3
  • Whats wrong with your solution ? Commented Dec 16, 2013 at 21:16
  • 1
    Check the "See also" section of array_slice documentation page Commented Dec 16, 2013 at 21:16
  • @zerkms thanks, missed this Commented Dec 16, 2013 at 21:18

2 Answers 2

1

PHP has a built-in function that does exactly this: array_chunk():

Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

Usage:

$arr = array(1,2,3,4,5,6,7,8,9,10);
$result = array_chunk($arr, 3);

Demo.

Sign up to request clarification or add additional context in comments.

Comments

1

A different approach using neither array_slice nor array_chunk

$flat = array( 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 );

$multi = array( ( $multiIndex = 0 ) => array( ) );

foreach( $flat as $value )
      count( $multi[ $multiIndex ] ) == 3
    ? $multi[ ++$multiIndex ] = array( $value )
    : $multi[ $multiIndex ][ ] = $value
    ;

var_dump( $multi );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.