phparrayssplitgrouping

Group values into comma-separated chunks


For example I have this values => 1,2,3,4,5,6,7,8

I want to split the values into 4-value strings: 1,2,3,4, 5,6,7,8

Using array_chunk(), I got this:

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

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

I do not know how to split and merge [0][1][2][3] into one array [0] => 1,2,3,4 and [1] => 5,6,7,8


Solution

  • You need to implode after you use array_chunk.

    $chunked = array_chunk([1,2,3,4,5,6,7,8], 4);
    
    foreach($chunked as $chunk) {
         $imploded[] = implode(',', $chunk);
    }
    
    print_r($imploded); // Array ( [0] => 1,2,3,4 [1] => 5,6,7,8 )