PHP reset Function | Set Internal Pointer to First Element

PHP reset is an inbuilt Function in PHP. It returns the first element of the array. Also, it sets the internal pointer to the first element of the array. It works opposite to PHP end Function. In this article, we will discuss the PHP reset Function.

Syntax

reset ($array)

Parameters

The function expects only one parameter. It is the array of which we want to reset the internal pointer.

Return Value

The function returns the first element of the array. Also, it sets the internal pointer to the first element. However, if the array is empty, it returns FALSE.

PHP reset Function

Examples

Let’s discuss a few examples of using the function.

Example 1: Simple Usage

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	$lastElement = end($testArray);
	print_r($lastElement);
	//Banana

	$firstElement = reset($testArray);
	print_r($firstElement);
	//Apple
?>

In the above example, first we set the internal pointer to the last element of the array. And then, using the reset function we reset it back to the first element.

Example 2: Empty Array

If the input array is empty, the function returns FALSE.

<?php

	$testArray = array();
	var_dump(reset($testArray));
	//bool(false)
?>

Example 3: Internal Pointer in function

For instance, consider an example demonstrating the Internal Pointer while using the function.

<?php

	$testArray = array('Apple', 'Mango', 'Banana');
	$lastElement = end($testArray); //The Array Pointer is set to the last element
	echo $lastElement;
	//Banana 

	$currentElement = reset($testArray); //Now the internal pointer points to the current element
	echo $currentElement;
	//Banana
?>
  • 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.
  • prev: Moves the internal pointer to the immediate previous element to the current element of the array.
  • end: Moves the internal pointer to the last element of the array.

Conclusion

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

Spread the Knowledge

Leave a Reply

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