Updated March 18, 2023
Introduction to 2D Arrays in PHP
An array is a collection of elements of any datatype. There are many data types in php like string, integer, boolean, array, object, resource…etc. A 2D array is a mix of these data types mainly the array. There are three different types of 2D Arrays in PHP which are the following:
- Numeric Array
- Associative Array
- Multidimensional Array
Types of 2D Arrays in PHP
These three Arrays are explained below:
1. The Numeric Array
The array with a numeric index.
Syntax:
array(value1, value2, value3, …);
Example:
$input = array(10,20,30,40,50);
2. The Associative Array
The array with string or number index. The elements of this array are stored in the form of a key-value pair.
Syntax:
array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3',…);
Example:
$input = array(0 =>Emma, 1=>Alice, 2=>'John');
3. The Multidimensional Array
The array of array is a multidimensional array or a 2D array or a nested array. This format is always an array or array. And thus called a nested array.
Syntax:
array (
array (elements...),
array (elements...),
...
)
Example:
$input = array(
array( "red", "green", "blue" ),
array( "yellow", "black", "white" )
);
In the above example, the input array is an example of a 2-dimensional array. Here, the main array contains 2 elements where each element is itself further an array of 3 elements.
How to Define 2D Arrays?
We learned that in the 2D array the value element is an array which further may have sub-arrays. The dimensions mentioned in an array is in the form of rows and columns. Keeping the tabular format of the array in mind it is easier to learn how to define these arrays. Meaning that if it is a two-dimensional array, two indices will be used, similarly, if it is a three-dimensional array, three indices will be used, and so on.
How to Create 2D Arrays?
Since we know how to define a 2D array we can create it now. Here the index is not defined and by default is a number that always starts with 0.
$input=array(
array( "red", "green", "blue" ),
array( "yellow", "black", "white" )
);
The array can also be defined in the form of the associative array.
(in key =>value form)
The index or the key is a string like colors, fruits, and cars. The value elements are in the form of an array containing 3 elements each.
$input = array(
'colors'=>array ("Red", "Green", "Blue"),
'fruits'=>array ("Apple", "Orange", "Grapes"),
'cars'=>array ("BMW", "Skoda", "Mercedes")
);
How to Access Elements of 2D Arrays?
To access these array values, you can make the use of square brackets. As you go deep inside more levels of the 2D array, the use of the set of square brackets will increase with each level.
Example #1
Code:
$input = array (
'colors' =>array ("Red", "Green", "Blue"),
'fruits' =>array ("Apple", "Orange", "Grapes"),
'cars' =>array ("Skoda", "BMW", "Mercedes")
);
Remember that the first set of square brackets contains the key which in this case are colors, fruits, cars. Followed by one more set of square brackets to traverse down the next level and can be accessed with numbers like 0,1,2.
So if we want to access the element “Grapes” in the above array,
echo $input['fruits'][2];
Similarly the following examples
If we want to access the element “Mercedes” in the array then
echo $input['cars'][2];
If we want to access the element “Red” in the array then
echo $input['colors'][0];
As the index always starts with 0 in an array.
Example #2
Code:
$input = array (
array ("Red", "Green", "Blue"),
array ("Yellow", "Orange", "Purple"),
);
If we want to access the element “Orange” in the above array, we will use the following line
echo $input[0][1];
will give “Green”
echo $input[1][2];
will give “Purple”
echo $input[0][0];
will give “Red”
How to Insert Elements of 2D Arrays in PHP?
Since we know how to define, create and access array elements we will learn now how to insert elements in the array. There are array functions defined in PHP to work on multidimensional arrays like the array_push() function to insert, array_shift() function to remove and so on.
$input = array (
'colors'=>array ("Red", "Green", "Blue"),
'fruits'=>array ("Apple", "Orange", "Grapes"),
'cars'=>array ("Skoda", "BMW", "Mercedes")
);
Using print_r() function we will print the array firstly as it is.
Code:
//create multidimensional array
$input = array (
"colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
// print the multidimensional array
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
Now to add an element to fruits sub array we will use
array_push() function
Syntax:
array_push(array, value1,value2...)
Where,
- The array is the $input array
- value1 is the element to be added to the array
- value2, value3, are optional
Example #1
Code:
$input = array (
"colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
array_push($input['colors'], "Black");
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
In the below program we just remove the key “colors”, and found that it appends to the last of the given array with a 0 key as shown in the output image.
Example #2
Code:
// create multidimensional array
$input = array (
"colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
// adding a value to array
array_push($input, "Black");
// print the multidimensional array
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
Example #3
Code:
//create multidimensional array
$input = array (
array ("Red", "Green", "Blue"),
array ("Yellow", "Orange", "Purple")
);
//add a color to the array
array_push($input, "Black");
// print the multidimensional array
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
How to Update Elements of 2D Arrays in PHP?
To update an element of the 2D array just get the key from the array and replace the value of that key in a particular array.
$input['cars']['Mercedes'] = 'Duster';
Example #1
Code:
//create multidimensional array
$input = array (
"colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
//update the Mercedes with Duster
$input["cars"][2] = "Duster";
// print the multidimensional array
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
Example #2
Code:
//create multidimensional array
$input = array (
array ("Red", "Green", "Blue"),
array ("Yellow", "Orange", "Purple")
);
//update the Mercedes with Duster
$input[0][1] = "White";
// print the multidimensional array
echo "<pre>";
print_r($input);
echo "<pre>";
Output:
How to Delete Elements of 2D Arrays?
To delete an element of the 2D array we will use array_shift() function.
array_shift removes and returns the first element value of the array.
Syntax:
array_shift(array)
where
-array is the $input array
Example #1
Code:
//create multidimensional array
$input = array (
"colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
//print the removed element
print_r(array_shift($input));
Output:
Example #2
Code:
//create multidimensional array
$input = array (
array ("Red", "Green", "Blue"),
array ("Yellow", "Orange", "Purple")
);
//print the removed element
print_r(array_shift($input));
Output:
Two dimensional in Associative Array
In the following example, we have created a 2-d array containing the information of books like the author of the book, type of book, and published in the year. Also, we will learn how to traverse or loop through this array. Looping through the multidimensional array we will use a nested foreach loop. Meaning one foreach loop inside another foreach loop. The same can also be done using for loop.
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988
),
"Managing_Oneself" => array (
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
),
"Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
)
);
Just printing the above array without any loop will give us the following output:
Code:
// create multidimensional array
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988
),
"Managing_Oneself" => array (
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
),
"Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
)
);
// print the plain multidimensional array
echo "<pre>";
print_r($input);
echo "</pre>";
Output:
Now we will print the multidimensional array using a foreach loop.
Code:
// create multidimensional array
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988
),
"Managing_Oneself" => array (
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
),
"Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
)
);
//foreach to loop the outer array
foreach($input as $book) {
echo "<br>";
// foreach to loop the inner array
foreach($book as $key=>$value)
{
echo $key." ". $value. "<br>";
}
}
Output:
Conclusion
I hope this article is helpful to learn the concepts of the topic on a 2D array in PHP. This topic covers all the concepts required for the understanding related to the 2D array in PHP. This topic is made simpler with the help of examples with the output snapshots to refer to. According to the article, if all the programs are practiced well will surely help you to grasp the concepts easily. I hope the topic is made more informative for gaining more knowledge.
Recommended Articles
This is a guide to 2D Arrays in PHP. Here we discuss the three different types of the array in php and How to Update, Insert and Delete Elements of 2D Arrays with appropriate examples. You may also look at the following article.