Home > Article > Backend Development > 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:
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
These three Arrays are explained below:
The array with a numeric index.
Syntax:
array(value1, value2, value3, …);
Example:
$input = array(10,20,30,40,50);
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');
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.
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.
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") );
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.
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.
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”
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
Now to add an element to fruits sub array we will use
array_push() function
Syntax:
array_push(array, value1,value2...)
Where,
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
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.
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
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';
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
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
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:
Code:
//create multidimensional array $input = array ( array ("Red", "Green", "Blue"), array ("Yellow", "Orange", "Purple") ); //print the removed element print_r(array_shift($input));
Output:
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 ""; print_r($input); echo "";
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 "
"; // foreach to loop the inner array foreach($book as $key=>$value) { echo $key." ". $value. "
"; } }
Output:
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.
The above is the detailed content of 2D Arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!