PHP 8.3.4 Released!

current

(PHP 4, PHP 5, PHP 7, PHP 8)

currentLiefert das aktuelle Element eines Arrays

Beschreibung

current(array|object $array): mixed

Jedes Array hat einen internen Zeiger auf sein "aktuelles" Element, welcher auf das erste in das Array eingefügte Element initialisiert wird.

Parameter-Liste

array

Das Array.

Rückgabewerte

Die Funktion current() gibt den Wert des Array-Elements zurück, auf das der interne Zeiger gerade zeigt. Sie bewegt den Zeiger überhaupt nicht. Zeigt der interne Zeiger hinter das Ende der Elementliste, gibt current() false zurück.

Warnung

Diese Funktion kann sowohl das boolsche false zurückliefern, als auch einen nicht-boolschen Wert, welcher zu false ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Changelog

Version Beschreibung
8.1.0 Bei Objekten ist die Verwendung dieser Funktion veraltet. Stattdessen sollte entweder das Objekt vorher mit get_mangled_object_vars() in ein Array umgewandelt werden oder es sollten die Methoden einer Klasse verwendet werden, die Iterator implementiert, z. B. ArrayIterator.
7.4.0 Instanzen von SPL-Klassen werden nun wie leere Objekte behandelt, die keine Eigenschaften haben, anstatt die Iterator-Methode aufzurufen, die den gleichen Namen wie diese Funktion hat.

Beispiele

Beispiel #1 Beispiel für die Verwendung von current() und Freunden

<?php
$transport
= array('zu Fuß', 'Fahrrad', 'Auto', 'Flugzeug');
$mode = current($transport); // $mode = 'zu Fuß';
$mode = next($transport); // $mode = 'Fahrrad';
$mode = current($transport); // $mode = 'Fahrrad';
$mode = prev($transport); // $mode = 'zu Fuß';
$mode = end($transport); // $mode = 'Flugzeug';
$mode = current($transport); // $mode = 'Flugzeug';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Anmerkungen

Hinweis: Das Ergebnis des Aufrufs von current() auf ein leeres Array und auf ein Array, dessen interner Zeiger hinter das Ende der Elemente zeigt, sind nicht unterscheidbar von einem boolschen false-Element. Um ein Array, das möglicherweise false-Elemente enthält, korrekt zu durchlaufen, siehe die Kontrollstruktur foreach. Um current() dennoch zu verwenden und korrekt zu prüfen, ob der Wert tatsächlich ein Element des Arrays ist, sollte überprüft werden, ob sich der key() des current()-Elements im strikten Vergleich von null unterscheidet.

Siehe auch

  • end() - Positioniert den internen Zeiger eines Arrays auf dessen letztes Element
  • key() - Liefert einen Schlüssel eines Arrays
  • each() - Liefert das aktuelle Schlüssel-Wert-Paar eines Arrays und rückt den Arrayzeiger vor
  • prev() - Setzt den internen Arrayzeiger um ein Element zurück
  • reset() - Setzt den internen Zeiger eines Arrays auf sein erstes Element
  • next() - Rückt den internen Arrayzeiger vor
  • foreach

add a note

User Contributed Notes 15 notes

up
9
sergey dot karavay at gmail dot com
2 years ago
It looks like `current()` is deprectated for calling on objects since PHP 7.4.

Consider this code

```
$a = new ArrayIterator([1,2,3]);

var_dump(current($a), $a->current());
```

It returns
```
int(1)
int(1)
```

In PHP 7.3, but in PHP7.4 you get:
```
bool(false)
int(1)
```

And in PHP8:
```
Deprecated: current(): Calling current() on an object is deprecated in /in/fdrNR on line 5
bool(false)
int(1)
```
up
21
michael at squiloople dot com
12 years ago
current() also works on objects:

<?php

echo current((object) array('one', 'two')); // Outputs: one

?>
up
8
strate at yandex dot com
10 years ago
Note, that you can pass array by expression, not only by reference (as described in doc).

<?php
var_dump
( current( array(1,2,3) ) ); // (int) 1
?>
up
7
vaclav dot sir at gmail dot com
16 years ago
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
echo
"You are in the end of the array.";
} else {
echo
"Current element: " . current($array);
}
?>
up
7
retestro_REMOVE at SPAM_esperanto dot org dot il
21 years ago
The docs do not specify this, but adding to the array using the brackets syntax:
<?php $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

<?php
$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.
up
6
Vasily Yudin (st-2 at mail dot ru)
9 years ago
If you do current() after using uset() on foreach statement, you can get FALSE in PHP version 5.2.4 and above.
There is example:
<?php
$prices
= array(
0 => '1300990',
1 => '500',
2 => '600'
);
foreach(
$prices as $key => $price){
if(
$price < 1000){
unset(
$prices[$key]);
}
}

var_dump(current($prices)); // bool(false)
?>
If you do unset() without foreach? all will be fine.
<?php
$prices
= array(
0 => '1300990',
1 => '500',
2 => '600'
);
unset(
$prices[1]);
unset(
$prices[2]);

var_dump(current($prices));
?>
up
6
mdeng at kabenresearch dot com
19 years ago
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).
up
1
leozmm at outlook dot com
4 years ago
Array can be passed by both REFERENCE and EXPRESSION on `current`, because current doesn't move array's internal pointer,
this is not true for other functions like: `end`, `next`, `prev` etc.

<?php
function foo() {return array(1,2,3);}
echo
current(foo()); // this print '1'
echo end(foo()); // this print error: Only variables should be passed by reference
?>
up
1
xedin dot unknown at gmail dot com
5 years ago
Array functions, such as `current()` and `rewind()` will work on `Traversable` as well, PHP 5.0 - 7.3, but not in HHVM:

<?php

$queue
= new ArrayIterator(array('adasdasd'));
reset($queue);
$current = current($queue);
var_dump($current);

?>

See https://3v4l.org/VjCHR
up
2
vitalib at 012 dot net dot il
20 years ago
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;
?>
up
0
pdarmis at gmail dot com
6 years ago
Based on this example http://php.net/manual/en/function.current.php#116128 i would like to add the following. As Vasily points out in his example
<?php
$prices
= array(
0 => '1300990',
1 => '500',
2 => '600'
);
foreach(
$prices as $key => $price){
if(
$price < 1000){
unset(
$prices[$key]);
}
}

var_dump(current($prices)); // bool(false)
?>
The above example will not work and return false for version of PHP between 5.2.4 and 5.6.29. The issue is not present on PHP versions >= 7.0.1
A different workaround (at least from Vasily's example) would be to use reset() before using current() in order to reset the array pointer to start.
<?php
$prices
= array(
0 => '1300990',
1 => '500',
2 => '600'
);
foreach(
$prices as $key => $price){
if(
$price < 1000){
unset(
$prices[$key]);
}
}
reset($prices);
var_dump(current($prices)); // string(7) "1300990"
?>
up
0
gregory at gregory dot net
16 years ago
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
* DbRow file
* @package PalDb
*/

/**
* This class lets you use Db rows and object-relational mapping functionality.
*/

class DbRow implements Iterator
{
/**
* The DbResult object that gave us this row through fetchDbRows
* @var DbResult
*/
protected $result;

/**
* The fields of the row
* @var $fields
*/
protected $fields;

/**
* Constructor
*
* @param PDOStatement $stmt
* The PDO statement object that this result uses
* @param DbResult $result
* The result that produced this row through fetchDbRows
*/
function __construct($result)
{
$this->result = $result;
}

/**
* Get the DbResult object that gave us this row through fetchDbRows
* @return DbResult
*
* @return unknown
*/
function getResult()
{
return
$this->result;
}

function
__set(
$name,
$value)
{
$this->fields[$name] = $value;
}

function
__get(
$name)
{
if (isset(
$this->fields[$name]))
return
$this->fields[$name];
else
return
null;
}

/**
* Iterator implementation - rewind
*/
function rewind()
{
$this->beyondLastField = false;
return
reset($this->fields);
}

function
valid()
{
return !
$this->beyondLastField;
}

function
current()
{
return
current($this->fields);
}

function
key()
{
return
key($this->fields);
}

function
next()
{
$next = next($this->fields);
$key = key($this->fields);
if (isset(
$key)) {
return
$next[1];
} else {
$this->beyondLastField = true;
return
false; // doesn't matter what we return here, see valid()
}
}

private
$beyondLastField = false;
};

Hope this helps someone.
up
-4
Pratip Ghosh
9 years ago
If we unset any element from an array, and then try the current function, I noted it returned FALSE. To overcome this limitation, you can use array_values function to re-order the tree.
up
-8
aefxx
15 years ago
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
$key = key($array);
$copy = $array;

while ((
$copy_key = key($copy)) !== NULL) {
if (
$copy_key == $key) break;
next($copy);
}

return
$copy;
}
?>

That's all ... bye.
up
-8
jodevweb at gmail dot com
7 years ago
As Sergey stated a long time ago in this notes, when adding to the array using the brackets syntax, current won't return the last added value. Instead of moving the pointer with end(), you simply can get the last value with <?php $my_array[count($my_array) - 1] ?> (only applies to a non-associative array).
To Top