current() also works on objects:
<?php
echo current((object) array('one', 'two')); // Outputs: one
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
current — Retorna o elemento atual em um array
Todo array tem um ponteiro interno para o elemento "atual", o qual é inicializado para apontar para o primeiro elemento inserido em um array.
array
O array.
A função current() simplesmente retorna
o valor do elemento do array que está sendo apontado pelo
ponteiro interno. Ela não move o ponteiro de forma alguma. Se o
ponteiro interno aponta para além do final da lista de elementos ou o array está
vazio, current() retorna false
.
Esta função pode
retornar o valor booleano false
, mas também pode retornar um valor não booleano que pode ser
avaliado como false
. Leia a seção sobre Booleanos para mais
informações. Use o operador
=== para testar o valor retornado por esta
função.
Versão | Descrição |
---|---|
8.1.0 | Chamar esta função em objects tornou-se defasado. Converta o object para um array usando get_mangled_object_vars() primeiro ou, em vez disso, use os métodos fornecidos por uma classe que implementa Iterator, como ArrayIterator. |
7.4.0 | Instâncias de classes SPL agora são tratadas como objetos vazios que não possuem propriedades em vez de chamar o método da interface Iterator com o mesmo nome desta função. |
Exemplo #1 Exemplo do uso de current() e amigos
<?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) { }
?>
Nota: Os resultados de chamar current() em um array vazio e em um array, cujo ponteiro interno aponta para além do fim dos elementos, são indistinguíveis de um elemento bool
false
. Para percorrer adequadamente um array que pode conter elementosfalse
, veja a estrutura de controleforeach
. Para ainda usar current() e checar adequadamente se o valor é realmente um elemento do array, a key() do elemento current() deve ser verificada como estritamente diferente denull
.
foreach
current() also works on objects:
<?php
echo current((object) array('one', 'two')); // Outputs: one
?>
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)
```
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);
}
?>
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
?>
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.
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).
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));
?>
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
?>
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
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;
?>
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"
?>