Navigating through Arrays


PHP also includes a number of functions for navigating through arrays. That navigation is done with an array pointer, which holds the current location in an array. Here's how it works. Say you have this array:

 $vegetables[0] = "corn"; $vegetables[1] = "broccoli"; $vegetables[2] = "zucchini"; print_r($vegetables); echo "<BR>"; 

You can get the current element in this array with the current function:

 echo "Current: ", current($vegetables), "<BR>"; 

And you can move the pointer to the next element with the next function:

 echo "Next: ", next($vegetables), "<BR>"; 

The prev function moves the pointer back:

 echo "Prev: ", prev($vegetables), "<BR>"; 

The end function moves the pointer to the last element:

 echo "End: ", end($vegetables), "<BR>"; 

Want to move back to the beginning of the array? Use reset:

 reset($vegetables); 

And we can display the new current element, which will be the beginning of the array, like this:

 echo "Current: ", current($vegetables), "<BR>"; 

Let's put all this together in a web page, as you can see in Example 3-2, phpnavigate.php.

Example 3-2. Navigating through an array, phpnavigate.php
 <HTML>         <HEAD>             <TITLE>                 Navigating through an array             </TITLE>         </HEAD>         <BODY>             <H1>                 Navigating through an array             </H1>         <?php             $vegetables[0] = "corn";             $vegetables[1] = "broccoli";             $vegetables[2] = "zucchini";             print_r($vegetables);             echo "<BR>";             echo "Current: ", current($vegetables), "<BR>";             echo "Next: ", next($vegetables), "<BR>";             echo "Prev: ", prev($vegetables), "<BR>";             echo "End: ", end($vegetables), "<BR>";             echo "Resetting the array.<BR>";             reset($vegetables);             echo "Current: ", current($vegetables), "<BR>";         ?>     </BODY> </HTML> 

This page appears in Figure 3-2, where we've used the array pointer to move through an array. Very nice.

Figure 3-2. Navigating through an array.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net