PHP prev Function | Rewind Internal Pointer

PHP prev is an inbuilt function in PHP. It moves the internal pointer to the immediate previous element to the current element of the array. In this article, we will discuss the PHP prev Function.

Syntax

prev ($array)

Parameters

The function expects only one parameter. The input array is passed as the parameter to the function.

Return Value

The function returns the element which is immediately previous to the element the internal pointer is currently pointing to. However, if the array is empty, or there is no element previous to the current element, the function returns FALSE.

PHP prev Function

Examples

Example 1: Basic Usage

Let’s consider the following example of using the function.

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	
	echo current($testArray); //Apple. The first element is Apple

	echo next($testArray); //Mango. The next element is Mango

	echo prev($testArray); //Apple. The previous element of Mango is Apple.
?>

In the above example, first we move the internal pointer to the next of the current element. And then, we move back the internal pointer to the previous element.

Example 2: When the Previous Element Does Not Exist

For instance, consider a scenario when the previous element to the current element does not exist.

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	
	echo current($testArray); //Apple. The first element is Apple

	var_dump(prev($testArray)); //bool(false). There is no element previous to the current element
?>

In the above example, the function returns FALSE.

Related Functions

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	
	echo current($testArray); //Apple. The first element is Apple

	echo next($testArray); //Mango. The next element is Mango

	echo current($testArray); //Mango. Now the current element is Mango

	echo prev($testArray); //Apple. The previous element is Apple

	echo end($testArray); //Banana. The last element is Banana

	echo reset($testArray); //Apple. Moves the internal pointer back to the first element
?>
  • current: Returns the current position of the internal pointer.
  • next: Moves the internal pointer to the immediate next element to the current element of the array.
  • end: Moves the internal pointer to the last element of the array.
  • reset: Returns the internal pointer to the first element of the array.

Conclusion

In conclusion, we discussed the PHP prev Function. You can read more about it on the Official PHP Documentation. Additionally, you can learn about other PHP Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *