Multidimensional Arrays In PHP
PHP Multidimensional arrays contain one or more arrays as elements. Each array element is itself an array.
PHP provides a way to store and manage complex data structures through the use of multidimensional arrays.
In this article, we are going to explore the concept of PHP multidimensional arrays with examples in detail. Also, we will discuss how to create them, how to add and remove elements from them, and how to edit the data contained within them.
PHP Multidimensional Arrays
A PHP multidimensional array can have two, three, four, five, or more levels of depth, depending on the number of levels in the array. However, most people are unable to manage arrays that are more than three levels deep.
An array’s dimension helps you to determine how many indices you will need in order to locate an element in the array.
It takes two indices for an element to be selected in a two-dimensional array.
There are three indexes that need to be set for PHP multidimensional arrays in order to select an element from the array.
Let us start off by looking at the table below:
If we want to store the data in a two-dimensional array, we can do that as follows with PHP multidimensional arrays:
$fruits = array( array("Apple",35,22), array("Banana",15,10), array("Mango",48,35), array("Grapes",22,15) );
There are four arrays in the two-dimensional $fruits array, and each array has two indices: row and column.
In order to access the elements of the $fruits array, we need to refer to the two indices (row and column) as follows:
Above is an example of a PHP multidimensional array, where $user array is a two-dimensional array that stores the names and birth dates of several England cricket players.
The first dimension of the array represents each player, and the second dimension represents the player’s information, which is stored as an array of three elements: the player’s first name, last name, and birth date.
The for loop is used to iterate through the array and display information about each player.
The loop iterates 8 times, which corresponds to the number of players in the array.
The inner for loop iterates 3 times, which corresponds to the number of elements in the player’s information array.
For each element, the loop prints a list item with the corresponding information. Finally, the loop closes the unordered list tag.
The output of the code is a list of the England cricket players with their first name, last name, and birth date displayed in an ordered manner.