Page 153 - Open Soource Technologies 304.indd
P. 153

Unit 7: Multidimensional Arrays



            Objectives                                                                            Notes

            After studying this unit, you will be able to:
               •  Understand the concepts of multidimensional array
               •  Discuss how to extract the arrays
               •  Discuss how to perform conversion between arrays and variables
               •  Explain array traversal
               •  Understand the multidimensional array sorting
               •  Explain how to perform different operations on array
               •  Discuss the use of arrays

            Introduction

            A multidimensional array is an array that contains at least one other array as the value of one
            of the indexes.

            Arrays do not have to be a simple list of keys and values each location in the array can
            hold another array. This way, we can create a two-dimensional array. You can think of a
            two-dimensional array as a matrix, or grid, with width and height or rows and columns.
            7.1 Concept of Multidimensional Array


            Array does not  have to be  a simple list of keys  and values;  each array  element  can  contain
            another array as a value, which in turn can hold other arrays as well. In such a way you can
            create two-dimensional or three-dimensional arrays.
               •    Two-dimensional Arrays
               •    Three-dimensional Arrays
            7.1.1 Two-dimensional Arrays

            Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles
            and prices. But if you need to keep more than one item of each type you need to use something
            different. One of the ways to do it is using multidimensional arrays. The table below might
            represent our two-dimensional array. Each row represents a type of flower and each column
            – a certain attribute.
                                   Table 7.1: Two-dimensional Arrays
                               Title        Price       Number
                               rose         1.25        15
                               daisy        0.75        25
                               orchid       1.15        7

            To store data in the form of array represented by preceding example using PHP, let’s prepare
            the following code:
                   Example:

            <?php
            $shop = array( array(“rose”, 1.25 , 15),
                           array(“daisy”, 0.75 , 25),
                           array(“orchid”, 1.15 , 7)
                         );
            ?>


                                             LOVELY PROFESSIONAL UNIVERSITY                                   147
   148   149   150   151   152   153   154   155   156   157   158