Bird
0
0

You have an array $data = [10, 20, 30]. You want to split it into chunks of size 2 and ensure each chunk has exactly 2 elements by padding with 0 if needed. Which code correctly achieves this?

hard📝 Application Q15 of 15
PHP - Array Functions
You have an array $data = [10, 20, 30]. You want to split it into chunks of size 2 and ensure each chunk has exactly 2 elements by padding with 0 if needed. Which code correctly achieves this?
A$chunks = array_chunk($data, 2); foreach ($chunks as &$chunk) { $chunk = array_pad($chunk, 2, 0); } print_r($chunks);
B$chunks = array_pad(array_chunk($data, 2), 2, 0); print_r($chunks);
C$chunks = array_chunk(array_pad($data, 5, 0), 2); print_r($chunks);
D$chunks = array_chunk($data, 2, 0); print_r($chunks);
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want chunks of size 2, each chunk exactly length 2, padding with 0 if chunk is smaller.
  2. Step 2: Analyze each option

    $chunks = array_chunk($data, 2); foreach ($chunks as &$chunk) { $chunk = array_pad($chunk, 2, 0); } print_r($chunks); splits into chunks, then pads each chunk to size 2 with 0, which is correct.
    $chunks = array_pad(array_chunk($data, 2), 2, 0); print_r($chunks); tries to pad the array of chunks, which is incorrect.
    $chunks = array_chunk(array_pad($data, 5, 0), 2); print_r($chunks); pads the original array to size 5, then chunks, which may add unwanted extra elements.
    $chunks = array_chunk($data, 2, 0); print_r($chunks); passes 0 as third argument to array_chunk, which is invalid.
  3. Final Answer:

    $chunks = array_chunk($data, 2); foreach ($chunks as &$chunk) { $chunk = array_pad($chunk, 2, 0); } print_r($chunks); -> Option A
  4. Quick Check:

    Pad each chunk after chunking [OK]
Quick Trick: Pad each chunk after chunking, not the whole array [OK]
Common Mistakes:
  • Padding the whole array before chunking
  • Passing extra arguments to array_chunk
  • Trying to pad the array of chunks directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes