Array Functions
Advertisements

PHP prev() Function

Topic: PHP Array ReferencePrev|Next

Description

The prev() function moves the array's internal pointer to the previous element and returns its value.

The following table summarizes the technical details of this function.

Return Value: Returns the value of the previous element in the array, or FALSE if the array is empty.
Version: PHP 4+

Tip: Every array has an internal pointer that points to the current element in the array. When a new array is created, the current pointer is initialized reference the first element in the array.


Syntax

The basic syntax of the prev() function is given with:

prev(array);

The following example shows the prev() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Getting the values
echo current($colors);  // Prints: red 
echo next($colors);     // Prints: green 
echo prev($colors);     // Prints: red
?>

Parameters

The prev() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.

More Examples

Here're some more examples showing how prev() function actually works:

The following example demonstrates how to get the previous value from an associative array:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Getting the element's values
echo current($alphabets); // Prints: apple
echo next($alphabets);    // Prints: ball
echo prev($alphabets);    // Prints: apple

// Getting the previous element's key
echo key($alphabets); // Prints: a
?>

The prev() function is commonly used along with the following functions:

  • current() – Returns the value of the current element in an array.
  • next() – Moves the internal pointer of an array to the next element, and returns its value.
  • end() – Moves the internal pointer of an array to its last element, and returns its value.
  • reset() – Set the internal pointer of an array to its first element, and returns its value.
  • key() – Returns the key of the current element in an array.

Here's an example that demonstrates how these functions basically work:

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Getting the values 
echo current($colors);  // Prints: red
echo end($colors);      // Prints: black
echo current($colors);  // Prints: black
echo prev($colors);     // Prints: yellow
echo current($colors);  // Prints: yellow
echo next($colors);     // Prints: black
echo current($colors);  // Prints: black
echo reset($colors);    // Prints: red
echo current($colors);  // Prints: red

// Getting the current element's key
echo key($colors);      // Prints: 0
?>
Advertisements
Bootstrap UI Design Templates