Here is a simple loop
$list = array("A", "B", "C","D");
foreach ($list as $var) {
print(current($list));
}
Output (demo)
BBBB // Output for 5.2.4 - 5.5.0alpha4
BCD // Output for 4.4.1
AAAA // Output for 4.3.0 - 4.4.0, 4.4.2 - 5.2.3
Question :
- Can someone please explain whats going on ?
- Why am i not getting ABCD
- Even if a copy of the array was made by
foreach
i should be gettingAAAA
but not getting that in the currentPHP
stable version
Note* I know i can simply use print $var
but the from PHP DOC
current — Return the current element in an array 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. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns FALSE.
Update 1 - New Observation
Thanks to Daniel Figueroa : Just by wrapping current
in a function you get different result
foreach ( $list as $var ) {
print(item($list));
}
function item($list) {
return current($list);
}
Output ( Demo )
BCDA // What the hell
Question :
- Why not getting "BBBB" ?
- How does wrapping current in a function affect
foreach
output ? - Where did the extra "A" Come from ?
Update 2
$list = array("A","B","C","D");
item2($list);
function item2($list) {
foreach ( $list as $var ) {
print(current($list));
}
}
Output ( See Demo )
AAAA // No longer BBBB when using a function
Question :
- What is the different running a loop in a function and running it outside a function because you get
AAAA
outside andBBBB
in a function in most PHP version