FROM PHP.net
The current() function simply returns the value of the array element
that's currently being pointed to by the internal pointer. It does not
move the pointer in any way
then: use next()
$list = array("A", "B", "C","D");
foreach ($list as $var) {
print(current($list));
next($list);
}
NOTE: the first element will not be printed because foreach moved the pointer to second element of the array :)
This example will explain the full behaviour:
$list = array("A", "B", "C","D");
foreach ($list as $var) {
if(!isset($a)) reset($list); $a = 'isset';
print(current($list));
next($list);
}
out put is ABCD
Please also note that:
As foreach relies on the internal array pointer changing it within the loop
may lead to unexpected behavior.
foreach
EDIT: I want to share also my new confusing finding!!!
Example1:
$list = array("A", "B", "C","D");
$list_copy = $list;
foreach ($list as $key => $val) {
current($list_copy);
echo current($list);
//next($list);
}
OUTPUT: AAAA
Example2:
$list = array("A", "B", "C","D");
$list_copy = $list;
foreach ($list as $key => $val) {
current($list_copy);
echo current($list);
next($list);
}
OUTPUT: ABCD
When calling current() function inside foreach even for another array it will affect the foreach behavior...
Example3:
$list = array("A", "B", "C","D");
$refcopy = &$list;
foreach ($list as $key => $val) {
if(!isset($a)) { $a = 'isset'; reset($list); }
echo current($list);
next($list);
}
OUTPUT: ACD (WOW! B is missing)
Example: 4
$list = array("A", "B", "C","D");
$refcopy = &$list;
foreach ($list as $key => $val) {
echo current($list);
next($list);
}
OUTPUT: BCD
It can't be decided exactly what will happen inside foreach loop!!!