PHP Tutorial - PHP prev() Function






Definition

The prev() function moves the internal pointer to the previous element in the array and output its value.

Syntax

PHP prev() Function has the following syntax.

prev(array)

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to use
MethodDescription
next()moves the pointer to, and outputs the next element in the array
current()returns the value of the current element in an array
end()moves the pointer to, and outputs the last element in the array
reset()moves the pointer to the first element of the array
each()returns the current element key and value, and moves the pointer forward




Example 1

The next() and prev() functions move the cursor pointer forward or backward one element respectively, returning the value of the element now pointed to.

If cannot return a value, it will return false.


<?PHP
$array = array("A", "B", "C", "D", "E");
print end($array);

while($val = prev($array)) {
   print $val;
}
?>

The code above generates the following result.





Example 2

Using prev() and next() is more difficult when using arrays that have holes. For example:


<?PHP//from   ww w  .j a  va 2  s .c om
$array["a"] = "Foo"; 
$array["b"] = ""; 
$array["c"] = "Baz"; 
$array["d"] = "Wom"; 
print end($array); 

while($val = prev($array)) { 
        print $val; 
} 
?>

The empty value at key b causes both prev() and next() to return false, prematurely ending the loop.

The code above generates the following result.

Example 3

Output the value of the current, next and previous element in the array:


<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) . "\n";
echo next($people) . "\n";
echo prev($people);
?>

The code above generates the following result.

Example 4

A demonstration of all related methods:


<?php//from  w ww  . ja  v a  2 s  .  c om
$people = array("A", "B", "C", "D");

echo current($people) . "\n"; // The current element is A
echo next($people) . "\n"; // The next element of A is B
echo current($people) . "\n"; // Now the current element is B
echo prev($people) . "\n"; // The previous element of B is A
echo end($people) . "\n"; // The last element is D
echo prev($people) . "\n"; // The previous element of D is C
echo current($people) . "\n"; // Now the current element is C
echo reset($people) . "\n"; // Moves the internal pointer to the first element of the array, which is A
echo next($people) . "\n"; // The next element of A is B

print_r (each($people)); // Returns the key and value of the current element (now B), and moves the internal pointer forward
?>

The code above generates the following result.