phpday 2027 - Call for Papers

current

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

current — Restituisce l'elemento corrente di un array

Descrizione

function current(array|object $array): mixed

Ogni array ha un puntatore interno al suo elemento "corrente", che viene inizializzato al primo elemento inserito nell'array.

Elenco dei parametri

array

L'array.

Valori restituiti

La funzione current() restituisce semplicemente il valore dell'elemento dell'array a cui punta attualmente il puntatore interno. Non sposta il puntatore in alcun modo. Se il puntatore interno punta oltre la fine della lista degli elementi, oppure se l'array è vuoto, current() restituisce false.

Avviso

Questa funzione può restituire il valore Booleano false, ma può anche restituire un valore non Booleano che viene valutato come false. Si legga la sezione sui Booleani per maggiori informazioni. Usare l'operatore === per verificare il valore restituito da questa funzione.

Log delle modifiche

Versione Descrizione
8.1.0 Chiamare questa funzione sugli object è deprecato. Convertire prima l'object in un array usando get_mangled_object_vars(), oppure usare invece i metodi forniti da una classe che implementa Iterator, come ArrayIterator.
7.4.0 Le istanze delle classi SPL ora sono trattate come oggetti vuoti privi di proprietà, invece di chiamare il metodo di Iterator con lo stesso nome di questa funzione.

Esempi

Example #1 Esempio di utilizzo di current() e delle funzioni correlate

<?php
$transport = array('piedi', 'bici', 'auto', 'aereo');
echo $mode = current($transport), PHP_EOL; // $mode = 'piedi';
echo $mode = next($transport), PHP_EOL;    // $mode = 'bici';
echo $mode = current($transport), PHP_EOL; // $mode = 'bici';
echo $mode = prev($transport), PHP_EOL;    // $mode = 'piedi';
echo $mode = end($transport), PHP_EOL;     // $mode = 'aereo';
echo $mode = current($transport), PHP_EOL; // $mode = 'aereo';

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

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

Note

Nota:

I risultati della chiamata a current() su un array vuoto e su un array il cui puntatore interno punta oltre la fine degli elementi sono indistinguibili da un elemento false di tipo bool. Per attraversare correttamente un array che potrebbe contenere elementi false, vedere la struttura di controllo foreach.

Per usare comunque current() e verificare correttamente se il valore è davvero un elemento dell'array, occorre verificare che la key() dell'elemento current() sia strettamente diversa da null.

Vedere anche:

  • end() - Imposta il puntatore interno di un array al suo ultimo elemento
  • key() - Estrae una chiave da un array
  • each() - Restituisce la coppia chiave/valore corrente di un array e fa avanzare il cursore dell'array
  • prev() - Riporta indietro il puntatore interno dell'array
  • reset() - Imposta il puntatore interno di un array al suo primo elemento
  • next() - Fa avanzare il puntatore interno di un array
  • foreach

User Contributed Notes 11 notes

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

<?php

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

?>
up
7
sergey dot karavay at gmail dot com
5 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
10
vaclav dot sir at gmail dot com
19 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
9
retestro_REMOVE at SPAM_esperanto dot org dot il
23 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
7
strate at yandex dot com
13 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
6
mdeng at kabenresearch dot com
22 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
2
xedin dot unknown at gmail dot com
8 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
5
Vasily Yudin (st-2 at mail dot ru)
12 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
1
vitalib at 012 dot net dot il
23 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
leozmm at outlook dot com
7 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
pdarmis at gmail dot com
9 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"
?>
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top