Programs

Multidimensional Array in PHP [With Examples]

When we talk about storing values in PHP, we talk about the word array. To store multiple values, there are two ways of carrying out the task. One way is to assign each value to a single variable, and the other, much more efficient way, is to assign multiple values to a single variable. That is what we call an array. 

An array is a way to store multiple values in a single variable. Arrays, thus, form an important part of the programming communities go-to tools. Arrays can store both numeric as well as string values and can have multiple dimensions.

Thus, an array with more than one dimension is called a multidimensional array in PHP, which we’ll talk in great detail through hands-on examples later in the article.

To get a better sense of what an array is and its dimensions, let’s go through an example. 

Suppose you go to a supermarket and buy a pack of biscuits. When you open the pack, the biscuits are lined up one after the other. This means they are arranged in a linear fashion, and hence, this is an example of a one-dimensional array. 

Next, you think of buying a pack of assorted dry fruits. Now when you open the pack, there are slots both along the width and length of the box in which different dry fruits are kept. That forms an example of a two-dimensional array where the box represents the array, and the dry fruits in the slots make up the elements.

Read: PHP Project Ideas & Topics

Types & Characteristics

When we talk of arrays, we talk about them in two terms – what type an array is and what are its characteristics or attributes. The type of array is defined by its dimensions. By that virtue, there are two types: one-dimensional or single-dimensional and multidimensional array in PHP.

As already explained in the examples above, you must have gotten an idea of an array’s dimensions. So, to access an element is a one-dimensional array, you need just one index.

But to access an element in a multidimensional array in PHP, you require two indices for two-dimensional, three for three-dimensional array, and so on. Thus, a multidimensional array is defined as an array of arrays or sub-arrays, as the case may be.

The characteristics of an array can be classified as either numeric or associative.

  • Numeric array is an array which uses numbers to access its elements stored in the array.
  • Associative array uses strings or names to access the elements stored. For example, an employee’s name to access data from the company register or server.

Following is the syntax for defining a one-dimensional numeric array:

<?php

$variable name = array(‘index no.’ => ‘element’,…);

?>

Where,

‘$variable name’ is the name of the array

‘index no.’ refers to the index of the stored element

‘element’ refers to the stored value

Note that the default index number always starts with ‘0’.

Let’s look at an example

<?php

//Program for creating one dimensional numeric array

$Car Brands = array ( 0 => ‘BMW’,

                                  1 => ‘Land Rover’,

        2 => ‘Ferrari’,

       3 => ‘Ford’,

                                   4 => ‘Toyota’ );

Print_r($Car Brands);

?>

Output:

Array

(

  [0] => BMW

  [1] => Land Rover

  [2] => Ferrari

  [3] => Ford

  [4] => Toyota

)

As we can see from the output, the car brands are assigned to and accessed by numeric keys 0, 1, 2, …, etc.

Let’s take a look at a one-dimensional associative array; following is the syntax for the same:

<?php

$variable name = array( ‘string/key’ => ‘element’,…);

?>

Where,

‘$variable name’ is the name of the array

‘string/key’ refers to the id of the stored element

‘element’ refers to the stored value

Here’s an example of an associative one-dimensional array. Suppose we want to store the names of a few countries and the respective continent they lie in.

<?php

$Countries = array(

“Italy” => “Europe”,

                                  “India” => “Asia”,

                                  “Brazil” => “South America”

                                 “Mexico” => “North America”,

                          );

echo “Mexico is in” $Countries [“Mexico”];

?>

Output:

Mexico is in North America

Now it’s time to understand how a multidimensional array in PHP works. Here’s the syntax.

<?php

$variable name =array(

                           Array1( ‘string/key’ => ‘element’,…),

                           Array2( ‘string/key’ => ‘element’,…),…

                         );

?>

We can arrange arrays in terms of groups or patterns. For example, we can arrange car models based on their body types. Here’s an example code.

<?php

$Car body styles = array(

                        “SUV” => array( “Scorpio”, “Harrier”, “Creta”, “Seltos”, “Fortuner”),

                        “Hatchback” => array( “Swift”, “Jazz”, “Tiago”, “i20”)’

                      “MPV” => array( “Ertiga”, “Innova”, “Triber”)

                      );

Echo $Car body styles[“SUV”][3];

?>

Output:

Creta

Let’s quickly create a three-dimensional array by adding sales data to the previous example.

<?php

$Car body styles = array(

                                 “SUV” => array(

                                                          “Scorpio” => array(“Jan 20” =>“4521”, “Feb 20” => “3589”),

                                                          “Harrier” => array(“Jan 20” =>“1987”, “Feb 20”=> “2356”),

                                                          “Creta” => array(“Jan 20” => “10459”, “Feb 20” => “9887”),

                                                         “Seltos” => array(“Jan 20” => “12549”, “Feb 20” => “13589”),

                                                        “Fortuner” => array(“Jan 20” => “1897”, “Feb 20” => “1692”),

                                                       ),

     “Hatchback” => array(

                                                          “Swift” => array(“Jan 20” =>“19875”, “Feb 20” => “18521”),

                                                          “Jazz” => array(“Jan 20” =>“2451”, “Feb 20”=> “2390”),

                                                          “Tiago” => array(“Jan 20” => “6587”, “Feb 20” => “8850”),

                                                       ),

                             “MPV” => array(

                                                          “Ertiga” => array(“Jan 20” =>“5680”, “Feb 20” => “4920”),

                                                          “Innova” => array(“Jan 20” =>“2540”, “Feb 20”=> “2135”)

                          );

Echo “The sales of Creta for the month of Jan’ 20 are” $Car body styles[“SUV”][“Creta”][“Jan20”];

?>

Output:

The car sales of Creta for the month of Jan’ 20 are 10459

Must Read: PHP Interview Questions & Answers

Conclusion

So, we can conclude that arrays are an efficient and flexible form of data storage and access. Arrays can be stretched or compressed as per the need, which allows for easy modification. Associative multidimensional arrays help us group together related data. Apart from that, arrays help in achieving a clutter-free and cleaner code. Plus, you can perform a number of operations on an array, such as sorting, counting, etc.

If you’re interested to learn more about PHP, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

What is PHP?

PHP Hypertext Processor (abbreviated as PHP) is an open-source platform used for the scripting language. PHP has a general-purpose server-side scripting language which makes it suitable for various projects across the board. Being Operating Systems friendly, PHP can be operated on Windows, Linux, or Mac. It can also be accessed through web browsers and multiple database systems. PHP code can be embedded in HTML, making it easier to be used across multiple platforms without needing additional resources. PHP has a smooth learning curve due to its simpler syntax and clearly defined functions.

Can multi-dimensional arrays be created in JavaScript?

Multi-dimensional arrays are structured arrays that manage sub-arrays, allowing for multiple values to be assigned to a single variable within more than dimensions. Multi-dimensional arrays operate by storing indices for the array to ensure the smooth functioning of its elements. JavaScript is one of the most popular programming languages that work with HTML and CSS to dynamically update the web page’s user interface (UI) to increase the page’s functionality. However, JavaScript itself doesn’t have the function of creating multi-dimensional arrays like PHP. It lacks in-built structures to do so. However, multi-dimensional arrays can be made by inserting an array within a one-dimensional array.

What are multi-dimensional associative arrays?

Multidimensional arrays are essentially arrays within an array with multiple elements across many dimensions that help in reducing the time used for processing the details. Multidimensional associative arrays enable storage of key-value pair data brought together for group relations. This means that the data that seems essential and related to other relevant data are grouped. This can be done by assorting the key and value pairs within an array and connecting them to the parent key. This data assortment gives greater access to understanding the data and creates a clean structure.

Want to share this article?

Become a Full Stack Developer

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK SOFTWARE DEVELOPMENT
Learn More

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Let’s do it!
No, thanks.