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

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.

Example: In this approach, we directly access the first element using $arr[0] and the last element using $arr[count($arr) – 1].

PHP
<?php

// Get First and Last Array Elements
function getFirstAndLast(&$arr) {
    $first = $arr[0];
    $last = $arr[count($arr) - 1];
    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

Using reset() and end() Functions

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

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.

Example: The array_shift($arr) removes and returns the first element, and array_pop($arr) removes and returns the last element. Note that this method modifies the original array by removing these elements.

PHP
<?php

// Get First and Last Array Elements
function getFirstAndLast(&$arr) {
    $first = array_shift($arr);
    $last = array_pop($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

Contact Us