PHP Doku:: Liefert das aktuelle Element eines Arrays - function.current.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenArraysArray Funktionencurrent

Ein Service von Reinhard Neidl - Webprogrammierung.

Array Funktionen

<<count

each>>

current

(PHP 4, PHP 5)

currentLiefert das aktuelle Element eines Arrays

Beschreibung

mixed current ( array &$array )

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

Die Funktion current() liefert den Wert des Array Elements, auf das gerade vom internen Zeiger gezeigt wird. Sie bewegt den Zeiger in keinster Weise. Zeigt der interne Zeiger hinter das Ende der Elementenliste, gibt current() FALSE zurück.

Warnung

Diese Funktion kann sowohl das boolsche FALSE zurückliefern, als auch einen nicht-boolschen Wert, wie zum Beispiel 0 oder "", der von einem einfachen if-Statement als 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.

Hinweis: Es ist nicht möglich, das Ende eines Arrays von einem boolean FALSE-Wert zu unterscheiden. Um ein Array, das FALSE-Elemente beinhalten könnte, korrekt zu durchlaufen werfen Sie bitte einen Blick auf die each()- Funktion.

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

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

Siehe auch end(), key(), next(), prev(), reset() und each().


9 BenutzerBeiträge:
- Beiträge aktualisieren...
marc dot hanisch at nospam dot ateam dot de
19.05.2010 15:37
current() works with functions returning an array, too.
This is helpfull to get the first element of the returned array.

Note that current() with functions always returns the first element, because there is no variable the array was assigned to (and therefore no pointer).

Example:

<?php
//get the first element of the returned array
$element = current(get_my_arrays());
?>

In addition, current() with functions will not behave as assumed if your function returns an array reference and modifies the arrays pointer, of course!
aefxx
15.05.2008 17:39
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.
gregory at gregory dot net
28.02.2008 6:07
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.
vaclav dot sir at gmail dot com
13.08.2007 18:23
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);
}
?>
marnaq
18.08.2006 2: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.04.2004 8: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
2.12.2003 11: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
8.05.2003 13: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
2.03.2003 3:31
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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)