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, or false if 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 returns false.
  • 3. False Value Distinction: If an element contains a boolean false or empty value, prev() returns false for that element. Check key() !== null to 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 false when attempting to step back past the beginning of the array.