Home > Articles

chap3_0672323257

  • Print
  • + Share This

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";
}
?>
  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.