current

(PHP 3, PHP 4, PHP 5)

current -- 返回数组中的当前单元

说明

mixed current ( array &array )

每个数组中都有一个内部的指针指向它“当前的”单元,初始指向插入到数组中的第一个单元。

current() 函数返回当前被内部指针指向的数组单元的值,并不移动指针。如果内部指针指向超出了单元列表的末端,current() 返回 FALSE

警告

如果数组包含有空的单元(0 或者 "",空字符串)则本函数在碰到这个单元时也返回 FALSE。这使得用 current() 不可能判断是否到了此数组列表的末端。要正确遍历可能含有空单元的数组,用 each() 函数。

例子 1. current() 及相关函数的用法示例

<?php
$transport
= array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
?>

参见 end()key()next()prev()reset()


add a note add a note User Contributed Notes
marnaq
18-Aug-2006 08:20
To make this function return a reference to the element instead, use:

<?php
function &current_by_ref(&$arr) {
   return
$arr[key($arr)];
}
?>
mdeng at kabenresearch dot com
24-Apr-2004 02:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il
02-Dec-2003 06:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray
= array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo
'<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a
=& $myarray;
?>
tipman
08-May-2003 07:07
if you got a array with number as index you get the last index with this:

eg:
$array[0] = "foo";
$array[1] = "foo2";

$lastKey = sizeof($array) - 1;

only a little help :)
retestro_REMOVE at SPAM_esperanto dot org dot il
02-Mar-2003 10:31
The docs do not specify this, but adding to the array using the brackets syntax:
     $my_array[] = $new_value;
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.