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

Unit 7: Functions



            Therefore, the previous example can be rewritten as follows:                          Notes
            $arr1 = array(1, 2, 3);

            $arr2[] = 1;

            $arr2[] = 2;
            $arr2[] = 3;

            The result is the same as in the previous example.

            The same holds true for arrays with string keys:
            $arr1 = array(“name” => “Peter”, “age” => 28);

            $arr2[“name”] = “Peter”;

            $arr2[“age”] = 28;
            if ($arr1 == $arr2) {

            print ‘$arr1 and $arr2 are the same’ . “\n”;
            }

            The message confirming the equality of both arrays is printed.
            7.8.4 Reading Array Values

            You can use the $arr[key] notation to read array values. The next few examples build on top
            of the previous example:

            print $arr2[“name”];
            if ($arr2[“age”] < 35) {

            print “is quite young\n”;

            This example prints
            Peter is quite young

                          As  previously  mentioned,  using  the  $arr[]  syntax  is  not  supported  when
                          reading array indexes, but only when writing them.
            7.8.5 Accessing Nested Arrays (or Multi-Dimensional Arrays)

            When accessing nested arrays, you can just add as many square brackets as required to reach
            the relevant value. The following is an example of how you can declare nested arrays:
            $arr = array(1 => array(“name” => “Peter”, “age” => 28), array(“name”

            | → => “Barbara”, “age” => 67))

            You could achieve the same result with the following statements:
            $arr[1][“name”] = “Peter”;

            $arr[1][“age”] = 28;



                                             LOVELY PROFESSIONAL UNIVERSITY                                   115
   115   116   117   118   119   120   121   122   123   124   125