1

I have an array:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
)

I want to split the array into alternating chunks. (size 2 then 3 then 2 then 3 etc)

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 7
        )

    [3] => Array
        (
            [0] => 8
            [1] => 9
        )

)
2
  • Your example shows 3 then 2 then 3, 2 3 etc, i.e., it starts with 3 instead of 2 as in your text.
    – tomsv
    Aug 30, 2012 at 11:22
  • @dontomaso Either way is fine.
    – 472084
    Aug 30, 2012 at 11:23

6 Answers 6

5

That should work:

$a = array(0 => 0,1 => 1,2 => 2,3 => 3,4 => 4, 5 => 5, 6 => 6,7 => 7,8 => 8,9 => 9);
$chunks = array();
$i=1;
while(count($a)){
    $chunks[] = array_splice($a, 0,(2+($i%2)),array());

    $i++;
}

echo "<pre>";
var_dump($chunks);
1
  • 1
    This answer is missing its educational explanation. Aug 30, 2021 at 9:00
1

You can use array_splice for splitting the array, but you need to set conditions right? On what basis do you wanna split them?

And you can use array_merge to bring them back into an array of arrays.

In case of your current code, the code will be:

PHP Code

<?php
    $array = array(0,1,2,3,4,5,6,7,8,9);
    $final = array(
        array_splice($array, 0, 3),
        array_splice($array, 1, 2),
        array_splice($array, 1, 2),
        array_splice($array, 1, 2),
    );
    print_r($final);
?>

Output

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
        )

    [2] => Array
        (
            [0] => 6
            [1] => 7
        )

    [3] => Array
        (
            [0] => 8
            [1] => 9
        )

)

Fiddle here: http://codepad.org/JzxcZ2Q1

13
  • They just need to be split in the same order as the original array, like the example I gave. Can you show an example of how I can do it with these functions?
    – 472084
    Aug 30, 2012 at 11:25
  • Its done. Check out the example and the fiddle giving you the same output. @Jleagle Aug 30, 2012 at 11:30
  • 1
    @mickmackusa Happy to do that and thanks for the heads up. Will update it in a while. 😁 Aug 31, 2021 at 7:31
  • 1
    I hammer php questions all day long. I prefer to direct researchers to page that consist of correct, explained, and high-quality advice. In this way, I rely on others to maintain their own content. This is why I blow my whistle often. This is in no way an attack on you, but your post is not great content. I am delighted that you have agreed to edit it in the near future. Thanks. (I also have thousands of posts and it is very hard to maintain them all -- I like it when I am notified of a suboptimal answer because I only want to show researchers good coding practices.) Aug 31, 2021 at 7:39
  • 1
    I never discriminate pages based on age when I curate content for Stack Overflow. I cannot answer new questions because they are all duplicates. I have been combing Stack Overflow for days while cleaning up the insane number of redundant transpose questions. This is not a transposing question but I found it while searching. Stack Overflow has too much knowledge scattered in too many places and researchers are likely to miss a real gem. I think we, high-reppers, need to focus on cleaning up SO so that this place becomes the "Researchers' Paradise" that it was designed to be. Aug 31, 2021 at 7:44
1

Iterated calls of array_splice() seems like a great way to go. Here is a cleaner version of István Őri's answer. Subtracting from 5 removes the need to use the modulus operator.

Code: (Demo)

$array = range(1, 10);

$chunks = [];
$chunkSize = 3;

while ($array) {
    $chunkSize = 5 - $chunkSize;
    $chunks[] = array_splice($array, 0, $chunkSize);
}
var_export($chunks);

This snippet modifies $array as it iterates. array_splice() keeps removing elements from the front of the array. Eventually the array will become empty and the while() condition will fail -- breaking the loop.

0

You could use this, it isn't the most elegant, but it will just do the trick for you - and you can modify it nicely and adapt it to suit your purposes further:

<?php

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


$counter=count($originalArray);
$isTwo=true;
$newArray=array();
$arrElement=0;
$i=0;
while($i<$counter)
{
    if($isTwo)
    {
        $newArray[$arrElement]= array();
        for($j=0; $j<2; $j++)
        {
            $newArray[$arrElement][$j]=$originalArray[$i+$j];
        }
        $i+=2;
        $isTwo=false;
        $arrElement++;
    }
    else
    {
        $newArray[$arrElement]= array();
        for($j=0; $j<3; $j++)
        {
            $newArray[$arrElement][$j]=$originalArray[$i+$j];
        }
        $i+=3;
        $isTwo=true;
        $arrElement++;
    }
}
    var_dump($newArray);
?>

Output:

array(4) {
  [0]=>
  array(2) {
    [0]=>
    int(0)
    [1]=>
    int(1)
  }
  [1]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(3)
    [2]=>
    int(4)
  }
  [2]=>
  array(2) {
    [0]=>
    int(5)
    [1]=>
    int(6)
  }
  [3]=>
  array(3) {
    [0]=>
    int(7)
    [1]=>
    int(8)
    [2]=>
    int(9)
  }
}
0
$tobechunked_arr = array(0,1,2,3,4,5,6,7,8,9);
$chunk_size_arr = array(3,2,3,2);
$j = 0;
foreach($chunk_size_arr as $key => $val)
{
    for($i = 0; $i < $val; $i++)
    {
        $result_arr[$key][] = $tobechunked_arr[$j];
        $j++;
    }
}

echo "<pre>";
print_r($result_arr);
1
  • This code-only answer is not flexible. It requires the developer to know exactly how many elements are in $tobechunked_arr; otherwise it risks breaking. Aug 30, 2021 at 22:57
-1

try this

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Update

<?php 
$myArray = array("abc","def","ghi","jkl","mno","pqr","stu","vwx","yz");
$newArray = array_chunk($myArray, 2, false);
// Now process the multidimensional array made from array_chunk()
$i = 0;
foreach ($newArray as $inner_array) {
    $i++;
    echo "<h2>Chunk $i</h2>";
    while (list($key, $value) = each($inner_array)) {    
        echo "$key: $value <br />"; 
    }
}
?>

Output

Chunk 1

0: abc

1: def

Chunk 2

0: ghi

1: jkl

Chunk 3

0: mno

1: pqr

Chunk 4

0: stu

1: vwx

Chunk 5

0: yz

3
  • I need it to be in chunks of 2 AND 3
    – 472084
    Aug 30, 2012 at 11:24
  • This only splits it into chunks of 2
    – 472084
    Aug 30, 2012 at 11:33
  • try this $myArray = array("abc","def","ghi","jkl","mno","pqr","stu","vwx","yz"); $newArray = array_chunk($myArray, 2, false); // Now process the multidimensional array made from array_chunk() $i = 0; foreach ($newArray as $inner_array) { if($i==2 || $i==3) { echo "<h2>Chunk $i</h2>"; while (list($key, $value) = each($inner_array)) { echo "$key: $value <br />"; } } $i++; } Aug 30, 2012 at 11:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.