Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconMultidimensional Array in PHP [With Examples]

Multidimensional Array in PHP [With Examples]

Last updated:
24th Nov, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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.

Check out our free courses to get an edge over the competition.

Ads of upGrad blog

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.

Check out upGrad’s Java Bootcamp

Read: PHP Project Ideas & Topics

Learn Software engineering course online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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.

Check out upGrad’s Advanced Certification in Blockchain

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’.

Explore our Popular Software Engineering Courses

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);

?>

Explore Our Software Development Free Courses

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”];

?>

In-Demand Software Development Skills

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];

?>

Read our Popular Articles related to Software Development

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

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Ads of upGrad blog

 

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What 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.

2Can 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.

3What 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.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31584
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46947
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901332
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
52128
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909209
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34763
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902394
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26265
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4394
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon