3.7 Accessing the Current Element in an Array


You want to return the current element of an array to which PHP's internal pointer is pointing.

Technique

Use PHP's current() function, which returns the element to which the internal PHP pointer is currently pointing:

 <?php $current_element = current ($ar); ?> 

Comments

The current() function takes the specified array and returns the current element to which the internal array pointer points. However, if you are looking for information on iteratively processing arrays, I suggest you stay away from the current() function and use a while loop and the each() function:

 <?php while (list ($key, $element) = each ($ar)) {     print "key: $key, value: $element";  // print out $array } ?> 

Or, you could use a for loop to process the array:

 <?php for ($i = 0; $i < count ($ar); $i++) {     print $ar[$i]; } ?> 

However, a for loop is good only when the array has only contiguous numeric keys.

In PHP 4, you can use a foreach loop to process an array:

 <?php foreach ($ar as $element) {     print $element; } ?> 

or

 <?php foreach ($array as $key => $value) {     print "Key: $key, Value: $value"; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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