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().



current
mdeng at kabenresearch dot com
23-Apr-2004 11: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 02: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 04: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
01-Mar-2003 06: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.

<counteach>
 Last updated: Tue, 15 Nov 2005