What is the current() method in PHP?
The current() method is used to get the value of a current element pointed at by the array’s internal pointer (IP).
In
PHP, each array contains an internal pointer that points to the current element. It initially points to the first element of the array. We can move the pointer positions using methods likenext,prev, etc.
Syntax
current(array|object $array): mixed
Return value
The return is false if an array is empty or if the position pointed to by the internal pointer is beyond the array’s length.
Code
<?php$numbers = [1,2,3];// 1echo "Current Value is : ". current($numbers). "\n";//2next($numbers);echo "Current Value is : ". current($numbers). "\n";//3next($numbers);echo "Current Value is : ". current($numbers). "\n";// beyond length so falsenext($numbers);echo "Current Value is : ";var_dump(current($numbers));?>
Explanation
In the code above:
-
We created a
numbersarray. -
We used the
currentmethod to print the value pointed by the internal pointer of the array. -
We used the
nextmethod to move the pointer position one step forward and printed the value pointed by the pointer.
The
nextmethod moves the pointer position one step forward. We can use theprevmethod to move back.