Page 149 - Beginning PHP 5.3
P. 149

Chapter 6: Arrays



























                                    Figure 6-2

                           Notice how using these functions moves the array pointer forward and backward through the array (the
                         notable exceptions being   current()  and  key() , which simply return the current value or key without
                          moving the pointer).

                            Referring back to the sparse array example in the previous section on the   count()  function, you now
                          know how to retrieve the last element of the array without needing to know how it ’ s indexed:

                             // Create a sparse indexed array
                             $authors = array( 0 = >  “Steinbeck”, 1 = >  “Kafka”, 2= >  “Tolkien”, 47 = >

                             “Dickens” );

                             echo end( $authors ); // Displays “Dickens”
                           These functions are very useful, but there ’ s a slight problem with them. Each function returns  false  if an
                          element couldn ’ t be retrieved. This is all very well, but what if one or more of the elements in your array
                          actually contain the value   false ? In this case, when a function returns  false  you won ’ t know whether
                          you ’ re getting back the element ’ s value, or whether there was in fact a problem retrieving the element.

                            To get round this issue, you can use another PHP function:   each() . This returns the current element of
                          the array, then advances the pointer to the next element. Unlike the previous five functions, however,
                            each()  returns a four - element array rather than a value. This array contains both the key of the current
                         element, as well as its value. If an element couldn ’ t be retrieved  —  because the pointer has reached the

                         end of the array, or because the array is empty  —   each()  returns  false . This makes it easy to tell if

                            each()  has retrieved an element with the value of  false  —  in which case it returns the four - element
                          array  —  or if it couldn ’ t retrieve an element at all, in which case it returns   false .






                                                                                                         111





                                                                                                      9/21/09   9:00:12 AM
          c06.indd   111
          c06.indd   111                                                                              9/21/09   9:00:12 AM
   144   145   146   147   148   149   150   151   152   153   154