PHP Unconference Europe 2015

current

(PHP 4, PHP 5)

current配列内の現在の要素を返す

説明

mixed current ( array &$array )

各配列は、"カレント"の要素へのポインタを有しています。 このポインタは、その配列の最初の要素を指すように初期化されます。

パラメータ

array

配列。

返り値

current() 関数は、 単に内部ポインタが現在指している配列要素の値を返します。 この関数は、ポインタを全く移動しません。 内部ポインタが最終要素の次を指していたり 配列が空だったりした場合、 current()FALSE を返します。

警告

この関数は論理値 FALSE を返す可能性がありますが、FALSE として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

例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';

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

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

注意

注意: 配列中に boolean FALSE の要素が含まれていると、 それを配列の終わりと区別することができません。FALSE 要素を含む配列を順に処理するには、each() 関数を参照ください。

参考

  • end() - 配列の内部ポインタを最終要素にセットする
  • key() - 配列からキーを取り出す
  • each() - 配列から現在のキーと値のペアを返して、カーソルを進める
  • prev() - 内部の配列ポインタをひとつ前に戻す
  • reset() - 配列の内部ポインタを先頭の要素にセットする
  • next() - 内部配列ポインタを進める

add a note add a note

User Contributed Notes 9 notes

up
11
michael at squiloople dot com
2 years ago
current() also works on objects:

<?php

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

?>
up
6
vitalib at 012 dot net dot il
10 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
5
vaclav dot sir at gmail dot com
7 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
2
retestro_REMOVE at SPAM_esperanto dot org dot il
11 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
1
gregory at gregory dot net
6 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
1
mdeng at kabenresearch dot com
10 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
strate at yandex dot com
1 year 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
-5
aefxx
6 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
-3
Pratip Ghosh
5 months 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.
To Top