PHP reset() Function

What is PHP reset() Function?

If you want to move the internal pointer to the first element of an array, use reset() function in PHP. You’ll also get that first element as the return value of the function.

Syntax:

reset(array)

Parameters:

The Function has 1 parameter which is required-

array (Required): This specifies the input array.

Return Values:

The function returns-

  • The first element if the function is not empty. Check example 1.
  • FALSE if the array is empty. Check example 2.

Examples:

Example 1:

<?php
$language = ["PHP", "Python", "Java", "SQL", "HTML", "CSS", "JavaScript"];
$pointing_element = end($language);
echo "The internal pointer now on the element: " . $pointing_element . "<br />";
$pointing_element = reset($language);
echo "The first element of the array is: " . $pointing_element;
?>

Output:

The internal pointer now on the element: JavaScript
The internal pointer now on the element: PHP

Explanation:

The end() function moves the internal pointer at the last element in line #3. So, the pointer is now there. The reset() function moves the pointer to the first element in line 5. So, the element value at line #6 shows PHP.

Example 2:

<?php
$language = [];
$first_element = reset($language);
echo "The first element of the array is: ";
var_dump($first_element);
?>

Output:

The first element of the array is: bool(false)

Explanation:

As the array is empty, the reset() function returns FALSE.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP reset() Function

The reset() function is a built-in PHP function and part of the PHP’s array functions. It is a quick way to move the internal pointer to the first element no matter where it is located.

Reference:

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