Create a Multidimensional Array in PHP
This article provides a quick guide on how to create, structure, and manipulate multidimensional arrays in PHP. You will learn the basic syntax for both indexed and associative multidimensional arrays, how to access their nested values, and how to loop through them efficiently using code examples.
Understanding Multidimensional Arrays
In PHP, a multidimensional array is simply an array that contains one or more other arrays. This structure allows you to store complex, hierarchical data, such as database query results, matrix tables, or nested configurations.
Creating an Indexed Multidimensional Array
You can define a multidimensional array using either the traditional
array() syntax or the modern short array syntax
[].
Here is how to create a two-dimensional array representing a list of cars, their stock levels, and sold units:
$cars = [
["Volvo", 22, 18],
["BMW", 15, 13],
["Saab", 5, 2]
];To access the elements in this array, you must point to two indices: the row index and the column index.
echo $cars[0][0]; // Outputs: Volvo
echo $cars[1][2]; // Outputs: 13Creating an Associative Multidimensional Array
Associative multidimensional arrays are highly useful when you want to use named keys instead of numeric indices to make your data more readable.
$employees = [
"emp1" => [
"name" => "John Doe",
"role" => "Developer",
"salary" => 5000
],
"emp2" => [
"name" => "Jane Smith",
"role" => "Designer",
"salary" => 5500
]
];To access values in an associative multidimensional array, use the keys corresponding to each level:
echo $employees["emp1"]["name"]; // Outputs: John Doe
echo $employees["emp2"]["role"]; // Outputs: DesignerAdding and Modifying Elements
You can add new nested arrays or modify existing values using their specific keys or indices.
// Modifying an existing value
$employees["emp1"]["salary"] = 5200;
// Adding a new key-value pair to a nested array
$employees["emp1"]["email"] = "john@example.com";
// Adding a completely new array to the multidimensional array
$employees["emp3"] = [
"name" => "Mark Ruffalo",
"role" => "Manager",
"salary" => 7000
];Looping Through a Multidimensional Array
To iterate over a multidimensional array, you can nest
foreach loops. The outer loop iterates through the primary
elements, while the inner loop iterates through the sub-arrays.
foreach ($employees as $empId => $details) {
echo "Employee ID: " . $empId . "\n";
foreach ($details as $key => $value) {
echo "- " . ucfirst($key) . ": " . $value . "\n";
}
echo "\n";
}