Home »
PHP
PHP Array prev() Function (With Examples)
In this tutorial, we will learn about the PHP prev() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP prev() function
The prev() function firstly moves the current pointer to the previous element and returns the element.
Syntax
The syntax of the prev() function:
prev(arr);
Parameters
The parameters of the prev() function:
Return Value
The return type of this method is mixed, it returns the array value in the previous place that's pointed to by the internal array pointer, or false if there are no more elements. [Source]
Note
As we have discussed in previous tutorials (current() function and next() function) that an array has a pointer that points to the first element by default, next() function can be used to move the pointer to next element and then to print it and similarly a prev() function can be used to move the pointer to previous element and print it.
Sample Input/Output
Input:
$arr1 = array(10, 20, 30, 40, 50);
Function call:
current($arr1);
next($arr1);
prev($arr1);
Output:
10
20
10
Input:
$arr2 = array("name" => "Amit", "age" => 21, "Gender" => "Male");
Function call:
current($arr2);
next($arr2);
prev($arr2);
Output:
Amit
21
Amit
PHP prev() Function Example
<?php
$arr1 = array(10, 20, 30, 40, 50);
$arr2 = array("name" => "Amit", "age" => 21, "Gender" => "Male");
echo current($arr1) . "\n"; //print first element
echo next($arr1) . "\n"; //move to next element and print
echo prev($arr1) . "\n"; //move to previous element and print
echo current($arr2) . "\n"; //print first element
echo next($arr2) . "\n"; //move to next element and print
echo prev($arr2) . "\n"; //move to previous element and print
?>
Output
The output of the above example is:
10
20
10
Amit
21
Amit
To understand the above example, you should have the basic knowledge of the following PHP topics: