Using the PHP prev() Function: Syntax, Examples, and Tips
This article explains PHP's prev() function, detailing its syntax, usage examples—including basic calls, resetting pointers with reset(), reverse array traversal with while loops—and important considerations such as boundary behavior, providing clear code snippets for developers.
In PHP, the prev() function is a commonly used built‑in that moves the internal array pointer to the previous element and returns that element’s value.
prev() Function Syntax
prev(array &$array): mixed
The function accepts an array passed by reference so it can modify the internal pointer, and it returns the value of the element after the pointer moves.
Usage Example
A simple example demonstrates how to call prev() on an array:
$fruits = array("apple", "banana", "orange", "grape");
echo prev($fruits); // outputs: grapeIn this snippet, the array $fruits contains four elements; calling prev() moves the pointer from the end of the array to the last element ( grape ) and echoes its value.
Note that before using prev() , you should call reset() to move the internal pointer back to the first element, because PHP arrays start with the pointer at the first element by default.
Example with reset() and prev()
$fruits = array("apple", "banana", "orange", "grape");
reset($fruits); // reset pointer to first element
echo prev($fruits); // outputs: grapeHere reset() first positions the pointer at the start of the array, then prev() moves it to the last element and outputs it.
Reverse Traversal Using while Loop
$fruits = array("apple", "banana", "orange", "grape");
reset($fruits);
while ($fruit = prev($fruits)) {
echo $fruit . ", "; // outputs: grape, orange, banana, apple,
}The while loop repeatedly calls prev() to retrieve each element in reverse order until the function returns false , indicating the pointer has moved before the first element.
Important Note
When the pointer has moved before the first element, subsequent calls to prev() return false . Developers should check for this condition to avoid errors.
Summary
The prev() function is useful for obtaining the previous element of an array, performing reverse traversal, and handling pointer manipulation in PHP.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Course
Workerman+TP6 Real‑time Chat System Limited‑time Offer
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.