PHP
โฎ๏ธ PHP prev() Function: Rewinding the Array Pointer
The prev() function in PHP rewinds the internal array pointer by one element and returns the value of that previous element.
-
Return Value:
prev()returns the value of the element in the previous array position, orfalseif there are no more previous elements.
๐ ๏ธ Basic Usage & Pointer Rewinding
When you move the array pointer forward using next(), you can use prev() to step backward:
PHP
$fruits = ["Apple", "Pear", "Banana"];
// Move pointer to "Pear" then "Banana"
next($fruits); // Pointer at "Pear"
next($fruits); // Pointer at "Banana"
echo current($fruits); // Outputs: Banana
// Step backward to previous element
$previousFruit = prev($fruits);
echo $previousFruit; // Outputs: Pear
echo current($fruits); // Outputs: Pear
๐ Reverse Traversal with end() and prev()
You can move the pointer to the end of an array using end() and then traverse backward using prev():
PHP
$numbers = [10, 20, 30];
// Set pointer to the last element
end($numbers);
do {
echo key($numbers) . " => " . current($numbers) . "<br>";
} while (prev($numbers) !== false);
/*
Output:
2 => 30
1 => 20
0 => 10
*/
๐ Key Rules & Behaviors
-
1. Moves Before Returning: Like
next(),prev()shifts the pointer backward first, then reads and returns the element value. -
2. Start of Array Boundary: Calling
prev()when the pointer is at the very first element moves the pointer out of bounds and returnsfalse. -
3. False Value Distinction: If an element contains a boolean
falseor empty value,prev()returnsfalsefor that element. Checkkey() !== nullto distinguish actual boundary limits.
๐ Pointer Navigation Functions Comparison
| Function | Pointer Direction | Modifies Pointer? | Return Value |
|---|---|---|---|
next() |
Forward (+1) | โ Yes | Next element value (or false) |
prev() |
Backward (-1) | โ Yes | Previous element value (or false) |
reset() |
First Position | โ Yes | First element value (or false) |
-
๐ Short Summary
-
prev()moves the internal array pointer back one step and returns the target element value. - It directly updates the active internal pointer position of the array.
-
It returns
falsewhen attempting to step back past the beginning of the array.
