Broad Network


PHP Two Dimensional Array

PHP Multi-Dimensional Array with Security Consideration - Part 1

PHP 2D Indexed Array

Foreword: In this part of the series I discuss a simple way to create and use a two-dimensional array in PHP.

By: Chrysanthus Date Published: 23 Jan 2019

Introduction

This is part 1 of my series, PHP Multi-Dimensional Array. In this part of the series I discuss a simple way to create and use a two-dimensional array in PHP.

Pre-Knowledge
This series is part of the volume, PHP Course. At the bottom of this page, you will find links to the different series you should have read before coming here.

Need for a Two-Dimensional Array
You need a two dimensional array when you want to keep information of tabular (table) form. The following table has a list of products of a supermarket; the column headings are, ProductID Product Name, Category, Number, Cost Price and Selling Price

ProductID, ProductName, Category, Number, CostPrice, SellingPrice
1, TV Set, Entertainment, 50, 25, 30
2, DVD, Entertainment, 50, 20, 25
3, Clothe Box, Household, 45, 16, 21
4, Perfume, Beauty, 100, 2, 3
5, Banana, Fruit, 125, 5, 7
6, Pear, Fruit, 135, 3, 4

I will show you how to create a two-dimension (2D) array that will hold all these data in PHP.

Indexing in PHP Two-Dimensional Array
A two-dimensional array has rows and columns. Counting of rows begins from zero. Counting of columns also begins from zero. In PHP Two-Dimensional Array, you quote the row position (index) first before you quote the column position. So the value of [0][0] in the above table is, ProductID. This means the row concerned is row zero and the column concerned is column zero. The value of [1][0] in the above table is, 1. The value of [0][1] in the above table is, ProductName. The value of [2][1] is, DVD; and so on.

Creating a Two-Dimensional Array
You create an empty two-dimensional array in the same way that you create an empty one-dimensional array. Let the name of our two dimensional array be arr. So you would create the empty two-dimensional array as follows:

    $arr;

Accessing an Array Element
You access an element in a two dimensional array with the following syntax:

    $arrayName[rowIndex][columnIndex]

I present examples below.

Placing Elements into a 2D Array One-by-One
You can place elements into a two-dimensional array one-by-one. You do this using the square brackets and the corresponding indices (row and column numbers). The following code places the first and second rows of the above table into the array, one element at a time:

<?php
    
    $arr;

    $arr[0][0] = "ProductID";
    $arr[0][1] = "ProductName";
    $arr[0][2] = "Category";
    $arr[0][3] = "Number";
    $arr[0][4] = "CostPrice";
    $arr[0][5] = "SellingPrice";
    $arr[1][0] = 1;
    $arr[1][1] = "TV Set";
    $arr[1][2] = "Entertainment";
    $arr[1][3] = 50;
    $arr[1][4] = 25;
    $arr[1][5] = 30;

?>

Note: You can replace a value in a cell in the same way that you assign value for the first time. Also note the quotes used with strings above.

Reading Values from a 2D Array One-by-One
The syntax to read a value from a two-dimensional array into a variable is:

    $var = $arrayName[rowIndex][columnIndex];

So you read a value in a similar way that you place a value. The following code would place the first two rows of the above table into an array and then print them out from the array.

<?php
    
    $arr;

    $arr[0][0] = "ProductID";
    $arr[0][1] = "ProductName";
    $arr[0][2] = "Category";
    $arr[0][3] = "Number";
    $arr[0][4] = "CostPrice";
    $arr[0][5] = "SellingPrice";
    $arr[1][0] = 1;
    $arr[1][1] = "TV Set";
    $arr[1][2] = "Entertainment";
    $arr[1][3] = 50;
    $arr[1][4] = 25;
    $arr[1][5] = 30;

    for ($i=0; $i<2; ++$i)
        {
            for ($j=0; $j<6; ++$j)
                {
                    print $arr[$i][$j] . ", ";
                }
            print '<br>';        
        }

?>

Read and test the code. In a commercial program you would have to modify the code to remove the last comma displayed at the end of a row.

Placing Elements into a 2D Array Row-by-Row
You can place elements into a 2D array one row at a time. The syntax to place a row into a 2D array is:

    $arrayName[rowIndex] = array(value1, value2, value3, …);

The following program places all the rows of the above table into a 2D array and then displays them.

<?php
    
    $arr[0] = array("ProductID", "ProductName", "Category", "Number", "CostPrice", "SellingPrice");
    $arr[1] = array(1, "TV Set", "Entertainment", 50, 25, 30);
    $arr[2] = array(2, "DVD", "Entertainment", 50, 20, 25);
    $arr[3] = array(3, "Clothe Box", "Household", 45, 16, 21);
    $arr[4] = array(4, "Perfume", "Beauty", 100, 2, 3);
    $arr[5] = array(5, "Banana", "Fruit", 125, 5, 7);
    $arr[6] = array(6, "Pear", "Fruit", 135, 3, 4);

    for ($i=0; $i<7; ++$i)
        {
            for ($j=0; $j<5; ++$j)
                {
                    echo $arr[$i][$j] . ", ";
                }
            echo $arr[$i][5] . '<br>';        
        }

?>

Note that the string values are in quotes. Read and test the code.

Irregular Nature of a 2D Array
The above 2D array is regular in the sense that the edges of the array are straight. This means that you have equal number of columns (cells) for each row and equal number of rows (cells) for each column. In other words all the rows have elements for each cell and all the columns have elements for each cell. For the above array in the code, there are 6 cells per row and 7 cells per column; no cell is undefined.

It is possible to have a 2D array in PHP that is irregular. For a 2D PHP array, you do not have to place a new element (value) in the next “available” cell. The following code illustrates this:

    $arr;

    $arr[0][0] = "00";
    $arr[0][2] = "02";
    $arr[1][3] = "13";
    $arr[2][1] = "21";

This code would be executed. The array is irregular. This array would have been a 3-row-by-4-column array, judging from the maximum row and maximum column numbers. There are many cells, which are undefined (empty) for this array, e.g. cell [0][1].

2D Array by Initialization
“Array by Initialization” is a phrase I have borrowed from C++. It means creating an array where the left hand operand to the assignment operator is a variable and the right hand operand is the content (value) of the array. The content is within special symbols.

The right hand operand begins with [ and ends with ] immediately followed by “;”. Inside the square brackets pair, you have rows. Each row is a one-dimensional array. Each 1D row is delimited by square brackets pair. The 1D rows are separated by commas (,) and not semicolons (;). Within each 1D array, the items are separated by commas. There is no comma after the last item in a 1D row and no comma after the last 1D row. Read and test the following example that illustrates this:

<?php
    
    $twoDArr = [
                     ["ProductID", "ProductName", "Category", "Number", "CostPrice", "SellingPrice"],
                     [1, "TV Set", "Entertainment", 50, 25, 30],
                     [2, "DVD", "Entertainment", 50, 20, 25],
                     [3, "Clothe Box", "Household", 45, 16, 21],
                     [4, "Perfume", "Beauty", 100, 2, 3],
                     [5, "Banana", "Fruit", 125, 5, 7],
                     [6, "Pear", "Fruit", 135, 3, 4]
                 ];

    print $twoDArr[2][1];

?>

The output is:

    DVD

Security Considerations
The insecurities and prevention of a 2D array can be deduced from those of a 1D array. I covered that in the series, PHP Arrays with Security Considerations.

That is it for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

NEXT

Comments