PHP prev() Function

What is PHP prev() Function?

PHP prev() function moves the internal pointer to the previous element and returns its value. Every array has an internal pointer that always points to one array element at any given time. That element is called the current element of that array which is initialized to the first element of the array.

Syntax:

prev(array)

Parameters:

The Function has 1 parameter which is required-

array (Required): This is the array which the array operates on.

Return Values:

The function returns –

  • The value of the previous element if success. Check example 1.
  • FALSE if there is no element on that position in the array. Check example 2.

Examples:

Example 1:

<?php
$array = array("CSS", "HTML", "PHP", "JavaScript");
echo "The value of the current element is: " . end($array);
echo "<br />";
echo "The value of the next element is: " . prev($array);
echo "<br />";
echo "The value of the next element is: " . prev($array);
echo "<br />";
echo "The value of the next element is: " . prev($array);
?>

Output:

The value of the last element is: JavaScript
The value of the previous element is: PHP
The value of the previous element is: HTML
The value of the previous element is: CSS

Example 2:

<?php
$array = array("CSS", "HTML", "PHP", "JavaScript");
echo "The value of the current element is: " . current($array);
echo "<br />";
echo "The value of the previous element is: ";
var_dump(prev($array));
?>

Output:

The value of the current element is: CSS
The value of the previous element is: bool(false)

Caution:

  • When the internal pointer is in the first element and you call this function, it returns false which shows an empty value. An empty element also returns the same value. To differentiate the two, check its type. Check example-
    <?php
    $array = array("", "HTML", "PHP", "JavaScript");
    echo "The value of the first element is: "; var_dump(current($array));
    echo "<br />";
    echo "The value of the previous element is: "; var_dump(prev($array));
    ?>
    

    Output:

    The value of the first element is: string(0) "" 
    The value of the previous element is: bool(false)

Difference between prev() Function and current() Function:

The prev() function moves the internal pointer to the previous element and returns it’s value, on the other hand, the current() function returns the value of the current element.

Difference between prev() Function and next() Function:

The prev() function moves the internal pointer to the previous element and returns it’s value, on the other hand, The next() function moves the internal pointer to the next element and returns it’s value.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP prev() Function

prev() is a built-in PHP array function that you can use to get the value of the previous element of the current internal pointer.

Reference:

https://www.php.net/manual/en/function.prev.php