PHP - Stepping Through an Array via element pointer

Introduction

To manipulate the pointer and access the elements that it points to, use the following functions:

FunctionDescription
current() Returns the value of the current element pointed to by the pointer, without changing the pointer position.
key() Returns the index of the current element pointed to by the pointer, without changing the pointer position.
next() Moves the pointer forward to the next element, and returns that element's value.
prev() Moves the pointer backward to the previous element, and returns that element's value.
end() Moves the pointer to the last element in the array, and returns that element's value.
reset()Moves the pointer to the first element in the array, and returns that element's value.

Each of these functions takes just one argument - the array - and returns the required element's value or index, or false if an element could not be found.

Here's an example script that uses each of these functions. You can see the result in Figure 6-2.

Demo

<?php

         $authors = array("A","B","C","D");

         echo"The array:". print_r($authors, true)."\n";

         echo"The current element is:". current($authors).".\n";
         echo"The next element is:". next($authors).".\n";
         echo"...and its index is:". key($authors).".\n";
         echo"The next element is:". next($authors).".\n";
         echo"The previous element is:". prev($authors).".\n";
         echo"The first element is:". reset($authors).".\n";
         echo"The last element is:". end($authors).".\n";
         echo"The previous element is:". prev($authors).".\n";

?>//from w  w w  .jav  a  2 s  .com

Result

For sparse array, you can retrieve the last element of the array without needing to know how it's indexed:

Demo

<?php

     // Create a sparse indexed array
     $authors = array(0 => "A", 1 => "B", 2=> "C", 47 =>"D");
     echo end($authors); // Displays"D"
?>/*ww w . ja  va 2  s .  co  m*/

Result

Related Topics