When working with arrays in PHP, it's common to need to get the current element's key and value while advancing the pointer to the next element. The built-in current() function returns the value at the current pointer position without moving it, while next() moves the pointer forward by one and returns the new current element. Using these two functions together allows easy traversal and detailed access to array elements.
The current() function returns the value of the array element at the current pointer position and does not change the pointer.
<span class="fun">current($array);</span>
$array = ["apple", "banana", "cherry"];
$current = current($array); // returns "apple"
The next() function advances the array pointer by one position and returns the value at the new pointer location.
<span class="fun">next($array);</span>
$array = ["apple", "banana", "cherry"];
$current = current($array); // "apple"
$next = next($array); // "banana"
To get the current key and value from an array and then move the pointer forward by one, you can combine key(), current(), and next().
$array = ["apple" => 1, "banana" => 2, "cherry" => 3];
$key = key($array); // gets current key "apple"
$value = current($array); // gets current value 1
next($array); // moves pointer to "banana"
This article has covered detailed methods for retrieving the current key-value pair and moving the pointer in PHP arrays using current() and next(). Mastering these techniques helps developers handle array data more efficiently.