Multidimensional Array in PHP

WBOY
Release: 2024-08-29 12:44:25
Original
264 people have browsed it

A multidimensional array is nothing extraordinary but an array inside another array. Each index of the array holds another array instead of a single element which again can be pointing to another array or particular elements. These sub-arrays inside the array are accessed using the multiple dimensions starting from the outer array and moving towards the inner array. Dimensions are basically the indices that are required to access or store the value at a particular position in an array. Multidimensional arrays in php are highly used in real-time applications but it is quite tricky to deal with them as a comparison to single dimensional arrays because of the multiple brackets and some complexity in order to work with them, either accessing or storing values at a particular index, use of loops are required.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

Below given is the general syntax of multidimensional arrays in PHP. Though multidimensional arrays in PHP can be 2D, 3D, 4D, and so on. The more dimensional array it is, the more difficult it is to manage them and more are the brackets added in front of the array name.

Syntax for 2D Array:

array(
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
)
Copy after login

Syntax for 3D Array:

array(
array (
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
),
array (
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
),
… so on
)
Copy after login

How to Declare Multidimensional Arrays in PHP?

PHP allows its multidimensional arrays to be either indexed or associative. Associative arrays are more interactive as compared to the indexed one. PHP allows a very simple way to declare a multidimensional array in PHP using the keyword ‘array’. In order to declare an array inside another array, We need to add the keyword ‘array’ and then the elements of that array.

1. Declaration of 2D Array in PHP

Code:

<?php
$employee_details = array();
$employee_details[ ] = array("Ram", "Agra", "Sr. Engineer");
$employee_details[ ] = array("Raghav", "Delhi", "Jr. Engineer");
?>
Copy after login

OR

<?php
$employee_details = array(
array("Ram", "Agra", "Sr. Engineer"),
array("Raghav", "Delhi", "Jr. Engineer"),
);
?>
Copy after login

The second Method Shown Above Is Commonly Used as It Is Quite Easy To Understand.

2. Declaration of 3D Array in PHP

Code:

<?php
/* Simplest way to declare a  3D array in Php in an indexed manner */
$item_details  = array(
array(
array ("item1", "abc", 100)),
array ("item2", "bcd", 200)),
array ("item3", "def", 300)),
),
array(
array ("item4", "abc4", 100)),
array ("item5", "bcd5", 200)),
array ("item6", "def6", 300)),
),
);
?>
Copy after login

The above declaration is purely indexed one of 3D arrays as there are no key-value pairs used for the association.

How to Initialize a Multidimensional Array in PHP?

Initializing a multidimensional array means assigning the values or elements at the particular position or indices of an array. Initializing a multidimensional array in PHP is quite easy like declaring. The only thing to keep in mind is the use of braces while initializing the subarrays. While initializing the values in a multidimensional array, the main array can be indexed or associative, in the example given below, the main array is the associative one having the keys Like Levis, Lee, Denizen, Etc.,

1. Initializing 2D Array in PHP

Code:

<?php
/* It is a multidimensional 2D array of clothes in which the main array holds another arrays of having 2 elements like cloth type and quantity */
/* It is associative kind of array having the data in the form of key => value pairs. So the data at the inner subarray is represented as associated by the key element.*/
$clothes = array(
"Levis" =>     array(
"Cloth_type" => "jeans",
"Quantity" => 20
),
"Pepe" =>        array(
"Cloth_type" => "jeans",
"Quantity" => 100
),
"Lee" =>      array(
"Cloth_type" => "tshirts",
"Quantity" => 50
),
"Denizen" =>   array(
"Cloth_type" => "tops",
"Quantity" => 80
)
);
?>
Copy after login

2. Initializing 3D Array in PHP

Initialization of 3D Arrays is the Same as the 2D arrays, the only difference between the two is the dimensions. The 3D Array requires 1 more index to initialize it than a 2D Array. The number the dimensions of array increases, the number of indices to initialize it also increases. In the example below, the main array is a simple indexed array having sub-arrays in itself. We can also make the main array in the below example as associative like we have done in a 2D array with the key as the brand name which makes it easier for the customer to understand while accessing and storing it.

Code:

<?php
/* In this there is a 3D array of clothes in which each element have an array of cloth type, brand and quantity of that particular brand. Each brand has different quantity and cloth type.*/
$clothes = array(
array(
array(
"Brand" => "Levis",
"Cloth_type" => "jeans",
"Quantity" => 20
),
array(
"Brand" => "Levis",
"Cloth_type" => "Tops",
"Quantity" => 100
)
),
array(
array(
"Brand" => "Lee",
"Cloth_type" => "jeans",
"Quantity" => 50
),
array(
"Brand" => "Lee",
"Cloth_type" => "tops",
"Quantity" => 80
)
),
);
?>
Copy after login

Accessing Multidimensional Arrays in PHP

Accessing of multidimensional arrays in PHP is very simple and is done by using either the for or for each loop which is the commonly used loops in PHP. For the indexed arrays, accessing of array elements can be done normally using the row and column number similar to other languages like C, Java, Etc. (arr[row_Num][column_Num]).

In the case of associative arrays, accessing of the elements of a multidimensional array is done using the key and value Pairs (key => Value). Though the elements are accessed through the simple for or for each loop. Please refer to the below-given example for a clear understanding of the accessing of elements in multidimensional arrays.

Types

There is no particular state till which the multidimensional arrays can exist in a PHP. It depends on the particular situation and scenario. Dimensions of an array varies accordingly. Normally programmers use 2D and 3D arrays because, after 3D arrays, it is a bit difficult to manage them.

As we have understood the declaration, initialization and accessing of multidimensional arrays in PHP, it is time for a quick brief explanation with examples.

1. 2D Array in PHP

2D arrays are basically array inside another array. Consider a scenario that a user have 10 books and each book has a different name, cost, type. In this case, the programmer can create an array of book numbers and each element of the main array holds the array which contains details of the book like name, cost, and type.

Code:

<!DOCTYPE html>
<html>
<body>
<?php
/* Multidimensional 2D array for 4 books and each book having a different array containing book name, cost and type. */
$books = array(
array("Fiction ", "Action and Adventure ", 800),
array("Fiction ", "Anthology ", 1000),
array("Non- Fiction ", "Biography ", 600),
array("Non- Fiction ", "Cook Book ", 900)
);
/* Accessing of a 2D array with the row_number and column_number */
for ($row_num = 0; $row_num < 4; $row_num++) {
echo "<p>Book number is  $row_num</p>";
for ($col_num = 0; $col_num < 3; $col_num++) {
// Accessing a particular element in a 2D array
echo $books[$row_num][$col_num];
}
echo "<br>";
}
?>
Copy after login

Output:

Multidimensional Array in PHP

2. 3D Array in PHP

3D arrays are an extension of 2D arrays. 3D arrays contain one more dimension and provides the chance to add more detailed information. Consider a scenario of employee array, in which employee have name, company and year and each employee has a company profile with the attributes id, skills, and profile. Each employee has personal data also with the details of the city, state, and country. In Order, to Store, the Above Data 3D Array Would Be Required.

Code:

<!DOCTYPE html>
<html>
<body>
<?php
$Employee = array(array(array("name", "company", "year"),
array("id","skills","profile"),
array("city","state","country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
<?php
echo "<ul>";
for ( $outermost = 0; $outermost < 3; $outermost++ )
{
echo "<li>The outermost number $outermost";
echo "<ul>";
for ( $row_num = 0; $row_num < 2; $row_num++ )
{
echo "<li> Now displaying the row number $row_num";
echo "<ul>";
for ( $col_num = 0; $col_num < 3; $col_num++ )
{
// accessing the array elements in a 3D array
echo "<li>".$Employee[$outermost][$row_num][$col_num]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>
</body>
</html>
Copy after login

Output:

Multidimensional Array in PHP

The above example clearly displays the details of the employee along with their skills in a very user-friendly manner. It allows the detailing of each and every employee in a fancy 3d arrays. We are dealing with 3d arrays, in order to access that, we need to first reach to the main array and then to the index which again holds the subarray and then to the elements of its subarray. In this way, accessing to the elements works in the case of multidimensional arrays starting from the outermost to the innermost array. similarly, in real life, there are sub-arrays or detailed things in which multidimensional arrays are used.

Conclusion

The above explanation clearly shows how the multidimensional arrays are used in php along with their basic syntax and initialization. Multidimensional arrays play an important role when it comes to working on real-life problems as they allow the user to store the data in a detailed form. Moreover, as shown above, php allows storing the multidimensional data either in indexed or associative form according to the requirements which makes it more friendly to access and store the data.

The above is the detailed content of Multidimensional Array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!