0
0
PHPprogramming~15 mins

Array chunk and pad in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Array chunk and pad
📖 Scenario: You are organizing a list of guests for a dinner party. You want to split the guests into tables with a fixed number of seats. If a table has fewer guests than seats, you want to fill the empty seats with the word "Empty".
🎯 Goal: Create a PHP program that splits an array of guest names into smaller arrays (tables) of a fixed size. If a table has fewer guests than the fixed size, fill the remaining seats with "Empty".
📋 What You'll Learn
Create an array called guests with exactly these names: 'Anna', 'Ben', 'Cara', 'David', 'Eva', 'Frank', 'Grace'
Create a variable called tableSize and set it to 3
Use array_chunk with the $preserve_keys parameter set to false to split guests into chunks of size tableSize
Use array_pad to fill any chunk smaller than tableSize with the string 'Empty'
Print the final array of tables
💡 Why This Matters
🌍 Real World
Organizing guests into tables for events or dinners where each table has a fixed number of seats.
💼 Career
Helps in understanding how to manipulate arrays for grouping data and filling missing values, useful in data processing and UI display tasks.
Progress0 / 4 steps
1
Create the guests array
Create an array called guests with these exact names: 'Anna', 'Ben', 'Cara', 'David', 'Eva', 'Frank', 'Grace'.
PHP
Need a hint?

Use square brackets [] to create the array and separate names with commas.

2
Set the table size
Create a variable called tableSize and set it to 3.
PHP
Need a hint?

Use the = sign to assign the value 3 to $tableSize.

3
Split guests into tables and pad
Use array_chunk with the $preserve_keys parameter set to false to split $guests into chunks of size $tableSize. Then, use a foreach loop with variables $index and $table to iterate over the chunks. Inside the loop, use array_pad to fill any chunk smaller than $tableSize with the string 'Empty'. Store the padded tables in a new array called paddedTables.
PHP
Need a hint?

Use array_chunk to split the array, then loop over each chunk and use array_pad to add 'Empty' if needed.

4
Print the padded tables
Print the array paddedTables using print_r to display the final tables with padding.
PHP
Need a hint?

Use print_r($paddedTables); to show the array structure.