0

I have the data in the array form as:

0 => a,
1 => b,
2 => c,
3 => d,
4 => e,
5 => f,
6 => g

How can I convert these array into the following one?

0 => array(0 => a, 1 => b),
1 => array(0 => c, 1 => d),
2 => array(0 => e, 1 => f),
3 => array(0 => g, 1 => null)

4 Answers 4

1

Iterate and pad each chunk to N elements. Demo

$n = 2;
var_export(
    array_map(fn($chunk) => array_pad($chunk, $n, null), array_chunk($array, $n))
);

Pad the input array to be evenly divisible by N, then chunk. Demo

$n = 2;
var_export(
    array_chunk(array_pad($array, $n * ceil(count($array) / $n), null), $n)
);

Unconditionally union a null-filled array to the last entry of a chunked array. Demo

$n = 2;
$result = array_chunk($array, $n);
$result[array_key_last($result)] += array_fill(0, $n, null);
var_export($result);
Sign up to request clarification or add additional context in comments.

Comments

0

Chunk will not give null as requested in case if number of elements is aliquant.

$by = 2;
$arr = range('a', 'g');
$arr = array_merge($arr, count($arr) % $by ?
       array_fill(0, $by - count($arr) % $by, null) : array()); 
var_dump(array_chunk($arr, $by));

Comments

0

User array_chunk() function to split an array into chunks, and 2nd param chunk size

array_chunk($arr, 2);

and if you want to keep the length of the chunk same then this code will work

$arr = range('a', 'g');
$size = 2;
$count = count($arr);
var_dump(
    array_chunk(
    array_merge($arr,$size <> $count ? array_fill(0, $size-($count%$size) : [], null)), 
    $size)
);

And php >=8.x shorthand code

var_dump(
   array_chunk(
    [...$arr, ...($size <> $count ? array_fill(0, $size-($count%$size), null):[])], 
        $size)
);

3 Comments

This is a provably incorrect answer. it doesn't generate the required null values.
Ok, I have added new piece of code, it will work as expected.
These snippets unnecessarily create two chunks when size = count. 3v4l.org/R0csP and 3v4l.org/XUk8K
-1

Live DEMO

Consider this code:

$j = 0;
for($i=0; $i< count($arr); $i++){
    if(($i !=0) && (($i % 2) == 0)){
        $j++;
    }
    $newArray[$j][] = $arr[$i];
}

$lastElement = count($newArray) -1;
if(count($newArray[$lastElement]) < 2){
    $newArray[$lastElement][]= null;
}
    
echo "<pre>";
print_r($newArray); 

Output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

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

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

)

Comments

Your Answer

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