How to use reset() and end() Functions In PHP

PHP provides built-in functions reset() and end() to access the first and last elements of an array.

Example: Here, reset($arr) moves the internal pointer to the first element and returns its value, while end($arr) moves the pointer to the last element and returns its value.

PHP
<?php

// Get First and Last Array Elements
function getFirstAndLast(&$arr) {
    $first = reset($arr);
    $last = end($arr);
    return [$first, $last];
}

// Driver code
$arr = [10, 20, 30, 40, 50];

list($first, $last) = getFirstAndLast($arr);

echo "First Element: $first, Last Element: $last";

?>

Output
First Element: 10, Last Element: 50

Get the First & Last Item from an Array in PHP

We will get the first and last elements of an array in PHP. This can be particularly useful in scenarios like processing data, working with queues, or implementing specific algorithms.

Below are the approaches to get the first and last items from an array in PHP:

Table of Content

  • Using Array Indexing
  • Using reset() and end() Functions
  • Using array_shift() and array_pop() Function

Similar Reads

Using Array Indexing

The basic method to access the first and last elements of an array is by using element indexing. The array indexing starts with 0....

Using reset() and end() Functions

PHP provides built-in functions reset() and end() to access the first and last elements of an array....

Using array_shift() and array_pop() Function

We can use array_shift() and array_pop() to retrieve and remove the first and last elements of an array, respectively....