19
For some time I always use the function current()
in PHP, to get the first element of array (which is actually not its functionality, as it returns the current pointer on which the array is) and I’ve been noticing something that has left me a little confused compared to the features of next()
, prev()
and reset()
.
And I’ll explain why.
In the PHP manual and even in Notepad++, we see that the argument of current()
is a reference passage of an element of the type array
, in the same way as next()
and prev()
.
In fact, the job declaration is this:
mixed current ( array &$array )
However, if you use it in a array function returned or even a array temporary (in this case, declared directly as argument of current()
) it works normally (the argument being a variable passed by reference).
current([1, 2, 3]);// 1
current(explode(',', '1, 2, 3')); //1
$array = [1, 2, 3];
current($array); //1
Now, what makes my confusion even bigger is that if I pass one array directly in functions such as next()
and prev()
, this generates a fatal error:
next([1, 2, 3]);
//Fatal error: Only variables can be passed by reference
echo next(explode(',', '1, 2, 3'));
//Strict Standards: Only variables should be passed by reference
The question is: If the PHP manual specifies in the function statement that current()
works with arrays
passed by reference (like many other functions used for arrays
), because she’s the only one who works with arrays passed directly as argument (as in the first example)?
Note: The PHP Handbook is very emphatic: mixed current ( array &$array )
I just discovered something important: using the PHP Sandbox, I noticed that the Current function started to behave like this from version 5.1 of PHP. Previously to this above version, when a parameter was passed that was not a variable in
current()
(because of the reference passage), this generated a fatal error. We can deduce that in the manual,mixed current ( array &$array )
is a reference to the way this function behaved in the old days.– Wallace Maxters
php is not reporting the use of
current()
correctly. The codecurrent(1)
generates Current() expects Parameter 1 to be array, integer Given, but if you docurrent(new stdClass)
, it generates no warning. If expera array, why accepts object?– Wallace Maxters