- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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"; } ?>