0
0
PHPprogramming~10 mins

Array chunk and pad in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to split the array into chunks of size 2.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$chunks = array_chunk($numbers, [1]);
print_r($chunks);
?>
Drag options to blanks, or click blank then click option'
A2
B3
C4
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 instead of 2 will create chunks of size 3.
Using 1 will create chunks of single elements.
2fill in blank
medium

Complete the code to pad the last chunk to size 3 with zeros.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$chunks = array_chunk($numbers, 3);
$last_chunk = $chunks[array_key_last($chunks)];
$padded = array_pad($last_chunk, [1], 0);
print_r($padded);
?>
Drag options to blanks, or click blank then click option'
A2
B3
C4
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Padding to 2 will not add enough elements.
Padding to 5 adds unnecessary zeros.
3fill in blank
hard

Fix the error in the code to pad the array to length 6 with -1.

PHP
<?php
$arr = [1, 2, 3];
$padded = array_pad($arr, [1], -1);
print_r($padded);
?>
Drag options to blanks, or click blank then click option'
A6
B3
C2
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 or less does not add padding.
Using 4 pads but not to the desired length 6.
4fill in blank
hard

Fill both blanks to create chunks of size 2 and pad each chunk to size 3 with 0.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$chunks = array_chunk($numbers, [1]);
foreach ($chunks as &$chunk) {
    $chunk = array_pad($chunk, [2], 0);
}
print_r($chunks);
?>
Drag options to blanks, or click blank then click option'
A2
B3
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 for chunk size creates bigger chunks.
Padding to 0 does not add elements.
5fill in blank
hard

Fill all three blanks to chunk the array by 3, pad each chunk to 4 with -1, and print the result.

PHP
<?php
$values = [10, 20, 30, 40, 50, 60, 70];
$chunks = array_chunk($values, [1]);
foreach ($chunks as &$chunk) {
    $chunk = array_pad($chunk, [2], [3]);
}
print_r($chunks);
?>
Drag options to blanks, or click blank then click option'
A3
B4
C-1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as padding value adds zeros instead of -1.
Padding to 3 does not add extra elements.