In PHP, a multidimensional array is simply an array within an array. It’s useful when you need to store complex data, like a table of records or a list of products with details.
🔹 Creating a Multidimensional Array
Here’s how to create a 2D array (array with arrays inside it):
<?php
// Creating a multidimensional array
$students = array(
array("Alice", 24, "Math"),
array("Bob", 22, "Physics"),
array("Charlie", 23, "Chemistry")
);
// Accessing elements
echo "Student: " . $students[0][0] . " - Age: " . $students[0][1] . " - Subject: " . $students[0][2];
?>
Output: Student: Alice - Age: 24 - Subject: Math
🔹 Associative Multidimensional Arrays
Using named keys makes data access easier.
<?php
// Creating an associative multidimensional array
$employees = array(
"emp1" => array("name" => "John", "age" => 30, "role" => "Developer"),
"emp2" => array("name" => "Jane", "age" => 28, "role" => "Designer"),
"emp3" => array("name" => "Dave", "age" => 35, "role" => "Manager")
);
// Accessing elements
echo "Employee: " . $employees["emp2"]["name"] . " - Role: " . $employees["emp2"]["role"];
?>
Output: Employee: Jane - Role: Designer
🔹 Looping Through a Multidimensional Array
Use nested foreach loops to access all elements.
<?php
$books = array(
array("Title" => "1984", "Author" => "George Orwell", "Year" => 1949),
array("Title" => "To Kill a Mockingbird", "Author" => "Harper Lee", "Year" => 1960),
array("Title" => "The Great Gatsby", "Author" => "F. Scott Fitzgerald", "Year" => 1925)
);
// Loop through the array
foreach ($books as $book) {
foreach ($book as $key => $value) {
echo "$key: $value <br>";
}
echo "<br>";
}
?>
Output:
Title: 1984
Author: George Orwell
Year: 1949
Title: To Kill a Mockingbird
Author: Harper Lee
Year: 1960
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Year: 1925
🔹 Adding & Modifying Elements
You can dynamically add or modify elements.
<?php
$movies = array(
array("title" => "Inception", "year" => 2010),
array("title" => "Interstellar", "year" => 2014)
);
// Adding a new movie
$movies[] = array("title" => "The Matrix", "year" => 1999);
// Modifying an element
$movies[1]["year"] = 2015;
print_r($movies);
?>
Output:
Array ( [0] => Array ( [title] => Inception, [year] => 2010 )
[1] => Array ( [title] => Interstellar, [year] => 2015 )
[2] => Array ( [title] => The Matrix, [year] => 1999 ) )
🎯 Key Takeaways
- Multidimensional arrays store arrays inside arrays.
- Use numeric keys or associative keys.
- Access elements using multiple indexes like
$array[0][1]or$array["key"]["subkey"]. - Use
foreachloops to iterate through all values. - Modify and add elements dynamically.
📝 Practice Time!
Create a multidimensional array of your favorite video games 🎮 and their release years!