2D Arrays in PHP

WBOY
Release: 2024-08-29 12:43:14
Original
702 people have browsed it

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!

Related labels:
php
source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!