Bird
Raised Fist0
PHPprogramming~10 mins

Multidimensional arrays in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Multidimensional arrays
Create outer array
↓
Add inner arrays as elements
↓
Access elements by multiple indexes
↓
Use nested loops to traverse
↓
Process or print each element
Start by creating an array that holds other arrays. Access elements using two or more indexes. Use nested loops to go through all elements.
Execution Sample
PHP
<?php
$matrix = [
  [1, 2],
  [3, 4]
];
echo $matrix[0][1];
?>
This code creates a 2x2 array and prints the element in the first row, second column.
Execution Table
StepActionVariable StateOutput
1Create outer array with two inner arrays$matrix = [[1,2],[3,4]]
2Access $matrix[0]Returns [1, 2]
3Access $matrix[0][1]Returns 2
4Print value 22
5End of script
💡 Script ends after printing the element at $matrix[0][1]
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
$matrixundefined[[1,2],[3,4]][[1,2],[3,4]][[1,2],[3,4]][[1,2],[3,4]]
$matrix[0]undefinedundefined[1,2][1,2][1,2]
$matrix[0][1]undefinedundefinedundefined22
Key Moments - 3 Insights
Why do we use two indexes like $matrix[0][1] to access elements?
Because $matrix is an array of arrays. The first index selects the inner array, the second index selects the element inside that inner array. See execution_table rows 2 and 3.
What happens if we try to access $matrix[2][0]?
Since $matrix has only two inner arrays (indexes 0 and 1), $matrix[2] does not exist. This will cause an error or undefined behavior. The execution_table shows valid indexes only.
How do nested loops help with multidimensional arrays?
Nested loops let us go through each inner array and then each element inside it, covering all elements. This is implied in the concept_flow step 'Use nested loops to traverse'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $matrix[0] at step 2?
A2
B[1, 2]
C[3, 4]
Dundefined
💡 Hint
Check the 'Variable State' column at step 2 in execution_table.
At which step does the code output the number 2?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Output' column in execution_table to find when '2' is printed.
If we add another inner array [5,6] to $matrix, how would the variable tracker change after step 1?
A$matrix would be [[1,2],[3,4],[5,6]]
B$matrix would be [[1,2],[3,4]] only
C$matrix would be [5,6]
D$matrix would be undefined
💡 Hint
Refer to the 'After Step 1' column in variable_tracker and imagine adding one more inner array.
Concept Snapshot
Multidimensional arrays are arrays inside arrays.
Access elements with multiple indexes like $array[row][col].
Use nested loops to visit all elements.
Useful for grids, tables, or matrices.
In PHP, arrays can hold arrays easily.
Remember indexes start at 0.
Full Transcript
This example shows how to create and use multidimensional arrays in PHP. We start by making an array that contains other arrays. Each inner array holds numbers. To get a number, we use two indexes: the first picks the inner array, the second picks the number inside it. The code prints the number 2 from the first inner array's second element. Variables keep their values until the script ends. Beginners often wonder why two indexes are needed or what happens if an index is missing. Nested loops help to go through all elements one by one. This is a simple way to handle tables or grids in code.

Practice

(1/5)
1. What is a multidimensional array in PHP?
easy
A. An array containing one or more arrays inside it
B. An array with only string keys
C. An array that can only hold numbers
D. An array that cannot be changed after creation

Solution

  1. Step 1: Understand array nesting

    A multidimensional array is an array that contains other arrays as its elements.
  2. Step 2: Identify the correct definition

    An array containing one or more arrays inside it correctly describes this nesting, while others describe unrelated properties.
  3. Final Answer:

    An array containing one or more arrays inside it -> Option A
  4. Quick Check:

    Multidimensional array = nested arrays [OK]
Hint: Think of arrays inside arrays like boxes within boxes [OK]
Common Mistakes:
  • Confusing multidimensional arrays with simple arrays
  • Thinking keys must be strings only
  • Believing arrays cannot be changed
2. Which of the following is the correct way to access the element 'blue' in this array?
$colors = [['red', 'green'], ['blue', 'yellow']];
easy
A. $colors[1][0]
B. $colors[0][2]
C. $colors[2][1]
D. $colors[1][1]

Solution

  1. Step 1: Identify the position of 'blue'

    'blue' is in the second inner array (index 1) and is the first element (index 0) there.
  2. Step 2: Use correct indices to access

    Accessing $colors[1][0] retrieves 'blue'. Other options point to wrong indices or elements.
  3. Final Answer:

    $colors[1][0] -> Option A
  4. Quick Check:

    Second array, first element = 'blue' [OK]
Hint: Count arrays and elements starting at zero [OK]
Common Mistakes:
  • Using wrong index numbers
  • Confusing first and second arrays
  • Trying to access non-existing elements
3. What will be the output of this PHP code?
$matrix = [[1, 2], [3, 4]];
echo $matrix[0][1] + $matrix[1][0];
medium
A. 9
B. 7
C. 5
D. Error

Solution

  1. Step 1: Identify the values at given indices

    $matrix[0][1] is 2 and $matrix[1][0] is 3.
  2. Step 2: Calculate the sum

    2 + 3 equals 5, so the output is 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    2 + 3 = 5 [OK]
Hint: Add values at given indices carefully [OK]
Common Mistakes:
  • Mixing up indices
  • Adding wrong elements
  • Expecting string output
4. Find the error in this code snippet:
$arr = [[1, 2], [3, 4];
echo $arr[1][1];
medium
A. Missing closing bracket for the first array
B. Missing closing bracket for the outer array
C. Incorrect index used to access element
D. Missing semicolon after echo statement

Solution

  1. Step 1: Check array syntax

    The array starts with [[ but only one closing bracket ] is present before the semicolon.
  2. Step 2: Identify missing bracket

    The outer array requires a closing bracket ], so the code should end with ]];
  3. Final Answer:

    Missing closing bracket for the outer array -> Option B
  4. Quick Check:

    Outer array brackets must match [OK]
Hint: Count opening and closing brackets carefully [OK]
Common Mistakes:
  • Confusing inner and outer brackets
  • Ignoring syntax errors
  • Assuming semicolon fixes bracket issues
5. Given this multidimensional array representing students and their scores:
<pre>$students = [
['name' => 'Alice', 'scores' => [85, 90]],
['name' => 'Bob', 'scores' => [78, 82]],
['name' => 'Charlie', 'scores' => [92, 88]]
];

Which code correctly calculates and prints the average score of Bob?
hard
A. $avg = array_sum($students[2]['scores']) / count($students[2]['scores']);
echo $avg;
B. $avg = array_sum($students['Bob']['scores']) / count($students['Bob']['scores']);
echo $avg;
C. $avg = array_sum($students[1]['score']) / count($students[1]['score']);
echo $avg;
D. $avg = array_sum($students[1]['scores']) / count($students[1]['scores']);
echo $avg;

Solution

  1. Step 1: Locate Bob's data in the array

    Bob is at index 1, and his scores are under the key 'scores'.
  2. Step 2: Calculate average correctly

    Use array_sum and count on $students[1]['scores'] to get average. $avg = array_sum($students[1]['scores']) / count($students[1]['scores']);
    echo $avg; does this correctly.
  3. Final Answer:

    $avg = array_sum($students[1]['scores']) / count($students[1]['scores']); echo $avg; -> Option D
  4. Quick Check:

    Index 1 and 'scores' key used correctly [OK]
Hint: Use numeric index for array, string keys for inner arrays [OK]
Common Mistakes:
  • Using string key for outer array
  • Misspelling 'scores' key
  • Using wrong index for Bob
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard