Table of Contents
Types of 2D Arrays in PHP
1. The Numeric Array
2. The Associative Array
3. The Multidimensional Array
How to Define 2D Arrays?
How to Create 2D Arrays?
How to Access Elements of 2D Arrays?
Example #2
How to Insert Elements of 2D Arrays in PHP?
How to Update Elements of 2D Arrays in PHP?
How to Delete Elements of 2D Arrays?
Two dimensional in Associative Array
Conclusion

2D Arrays in PHP

Aug 29, 2024 pm 12:43 PM
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 Tests

Start 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, …);
Copy after login

Example:

$input = array(10,20,30,40,50);
Copy after login

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',…);
Copy after login

Example:

$input =  array(0 =>Emma, 1=>Alice, 2=>'John');
Copy after login

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...),
...
)
Copy after login

Example:

$input = array(
array( "red", "green", "blue" ),
array( "yellow", "black", "white" )
);
Copy after login

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" )
);
Copy after login

The array can also be defined in the form of the associative array.

(in key =>value form)
Copy after login

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")
);
Copy after login

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")
);
Copy after login

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];
Copy after login

Similarly the following examples

If we want to access the element “Mercedes” in the array then

echo $input['cars'][2];
Copy after login

If we want to access the element “Red” in the array then

echo $input['colors'][0];
Copy after login

As the index always starts with 0 in an array.

Example #2

Code:

$input = array (
array ("Red", "Green", "Blue"),
array ("Yellow", "Orange", "Purple"),
);
Copy after login

If we want to access the element “Orange” in the above array, we will use the following line

echo $input[0][1];
Copy after login

will give “Green”

echo $input[1][2];
Copy after login

will give “Purple”

echo $input[0][0];
Copy after login

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")
);
Copy after login

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">";
Copy after login

Output:

2D Arrays in PHP

Now to add an element to fruits sub array we will use

array_push() function
Copy after login

Syntax:

array_push(array, value1,value2...)
Copy after login

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">";
Copy after login

Output:

2D Arrays in PHP

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">";
Copy after login

Output:

2D Arrays in PHP

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">";
Copy after login

Output:

2D Arrays in PHP

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';
Copy after login

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">";
Copy after login

Output:

2D Arrays in PHP

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">";
Copy after login

Output:

2D Arrays in PHP

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)
Copy after login

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));
Copy after login

Output:

2D Arrays in PHP

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));
Copy after login

Output:

2D Arrays in PHP

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
)
);
Copy after login

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 "
";
Copy after login

Output:

2D Arrays in PHP

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. "
"; } }
Copy after login

Output:

2D Arrays in PHP

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

See all articles