Current Location: Home> Latest Articles> end() + prev(): move the pointer in the array backwards

end() + prev(): move the pointer in the array backwards

M66 2025-06-02

In PHP, array pointers are controlled through built-in pointer functions. end() and prev() are two commonly used functions that operate on array pointers. You may already be familiar with how to use these functions to traverse or control the position of pointers in an array, but do you know how to move the array pointer backwards by combining these two functions?

This article will explain how the end() and prev() functions work, and with a simple example, it shows how to move the pointer backwards in an array.

end() function

The end() function is used to move the pointer of the array to the last element of the array and return that element. If the array is empty, return false . Examples are as follows:

 $array = array(1, 2, 3, 4, 5);
echo end($array);  // Output 5

In this code, end() will move the array pointer to the last element, i.e. 5 .

prev() function

The prev() function moves the array pointer forward by one position and returns the element at that position. If the array pointer is already on the first element of the array, it returns false . Examples are as follows:

 $array = array(1, 2, 3, 4, 5);
end($array);  // Move to the last element of the array
echo prev($array);  // Output 4

In this code, prev() will move the array pointer forward and output 4 .

Move the array pointer backward

If you want to move the pointer backwards in an array, you can use the end() and prev() functions in combination. First use end() to move to the last element of the array, and then use prev() to move the pointer backward. This allows you to gradually move the pointer backwards.

Here is an example showing how to move the pointer backward using end() and prev() :

 $array = array(1, 2, 3, 4, 5);

// Move the pointer to the end of the array
end($array);
echo current($array) . "\n";  // Output 5

// use prev() Move the pointer backward
prev($array);
echo current($array) . "\n";  // Output 4

prev($array);
echo current($array) . "\n";  // Output 3

In this example, end() moves the pointer to the end of the array, and then each call to prev() will move the pointer backward.

Summarize

The end() and prev() functions are very useful in PHP and can help us move pointers flexibly in arrays. By using these two functions, you can easily control the direction of the array pointer moving, and even have the pointer traverse the array in reverse.

If you have scenarios where you need to control the order of array pointers, you can try using these functions to enhance the flexibility of your code.