downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

each> <count
[edit] Last updated: Fri, 24 Jul 2009

view this page in

current

(PHP 4, PHP 5)

current배열의 현재 원소를 반환

설명

mixed current ( array &$array )

모든 배열은 "현재" 원소를 가리키는 내부 포인터를 갖는데, 이 내부 포인터는 배열에 삽입되어진 첫번째 원소로 초기화된다.

인수

array

배열.

반환값

current() 함수는 단순히 현재 내부 포인터에서 가리키고 있는 배열 원소의 값을 반환한다. 어떤 방법으로든 그 포인터를 움직이지 않는다. 내부 포인터가 원소 목록의 끝에서 벗어난 곳을 가리키면, current()FALSE를 반환한다.

Warning

이 함수는 논리 FALSE를 반환하지만, 0이나 "" 등, 논리 FALSE로 취급할 수 있는 다른 값을 반환할 수 있습니다. 자세한 정보는 논리형 섹션을 참고하십시오. 이 함수의 반환값을 확인하려면 === 연산자를 이용하십시오.

예제

Example #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) { }
?>

주의

Note: 배열의 끝과 boolean FALSE 원소를 구별할 수 없습니다. FALSE 원소를 가지는 배열을 올바르게 따라가려면, each()를 참고하십시오.

참고

  • end() - 배열 내부 포인터가 마지막 원소를 가리키게 설정
  • key() - 배열에서 키를 가져옵니다
  • each() - 배열에서 현재 키와 값 쌍을 반환하고 배열 커서를 전진
  • prev() - 내부 배열 포인터를 후진
  • reset() - 배열의 내부 포인터를 첫 원소로 설정
  • next() - 배열의 내부 배열 포인터를 전진



each> <count
[edit] Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes current
marc dot hanisch at nospam dot ateam dot de 19-May-2010 11:07
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 16-May-2008 01:09
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-Feb-2008 03:37
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 14-Aug-2007 01:53
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-Aug-2006 09:50
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 03:34
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 08:40
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 08:37
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 01:01
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.

 
show source | credits | sitemap | contact | advertising | mirror sites