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
- 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 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,
- 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 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.
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
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 class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
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 ""; 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:
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.
The above is the detailed content of 2D Arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
