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

Web Technologies-I



                   Notes         $prices = array( ‘Tires’=>100 );
                                 $prices[‘Oil’] = 10;
                                 $prices[‘Spark Plugs’] = 4;
                                 Here  is  another  slightly  different,  but  equivalent  piece  of  code.  In  this  version,  we  do  not
                                 explicitly create an array at all. The array is created for us when we add the first element to it.
                                 $prices[‘Tires’] = 100;
                                 $prices[‘Oil’] = 10;
                                 $prices[‘Spark Plugs’] = 4;

                                 Using Loops with Associative Arrays
                                 Because the indices in this associative array are not numbers, we cannot use a simple counter in
                                 a for loop to work with the array. We can use the foreach loop or the list() and each()constructs.
                                 The foreach loop has a slightly different structure when using associative arrays. We can use it
                                 exactly as we did in the previous example, or we can incorporate the keys as well:
                                 foreach ($prices as $key => $value)
                                  echo $key.’=>’.$value.’<br />’;
                                 The following code lists the contents of our $prices array using the each() construct:

                                 while( $element = each( $prices ) )
                                 {
                                  echo $element[ ‘key’ ];
                                  echo ‘ - ‘;
                                  echo $element[ ‘value’ ];
                                  echo ‘<br />’;
                                 }

                                 The output of this script fragment is shown in Figure 6.1.

                                           Figure 6.1: An each() Statement can be used to Loop Through Arrays































        130                               LOVELY PROFESSIONAL UNIVERSITY
   131   132   133   134   135   136   137   138   139   140   141