Current Location: Home> Latest Articles> PHP Array Operations: Methods to Get the First and Last Element of an Array

PHP Array Operations: Methods to Get the First and Last Element of an Array

gitbox 2025-06-17

Introduction to PHP Arrays

In PHP, arrays are an important data type that allows you to store multiple values, which can be accessed through a single variable. The elements of an array can be of various types, including numbers, strings, and other data types. Using arrays to manage multiple values is more efficient and convenient compared to using multiple individual variables.

Declaring a PHP Array

In PHP, arrays are declared using the array

In this example, the variable $arr is an array containing three elements: "apple," "banana," and "orange."

Getting the First Element of a PHP Array

There are several common methods to retrieve the first element of a PHP array. Here are two common ways:

Method 1: Using Array Indexing

Since PHP arrays are zero-indexed, the index of the first element is 0. Below is an example:


$arr = array('apple', 'banana', 'orange');
$first_element = $arr[0];
echo "The first element is: " . $first_element;
        

Output: The first element is: apple

Method 2: Using PHP's Built-in Function array_shift()

The array_shift() function removes and returns the first element from an array. Here’s an example:


$arr = array('apple', 'banana', 'orange');
$first_element = array_shift($arr);
echo "The first element is: " . $first_element;
        

Output: The first element is: apple

Getting the Last Element of a PHP Array

Similarly, there are multiple ways to retrieve the last element of a PHP array. Here are two common methods:

Method 1: Using Array Indexing

You can calculate the index of the last element by using the count() function to get the length of the array. Here’s an example:


$arr = array('apple', 'banana', 'orange');
$last_element = $arr[count($arr) - 1];
echo "The last element is: " . $last_element;
        

Output: The last element is: orange

Method 2: Using PHP's Built-in Function array_pop()

The array_pop() function removes and returns the last element from an array. Here’s an example:


$arr = array('apple', 'banana', 'orange');
$last_element = array_pop($arr);
echo "The last element is: " . $last_element;
        

Output: The last element is: orange

Conclusion

This article has explained how to retrieve the first and last elements of a PHP array using a couple of common methods. You can either use array indexing or PHP's built-in functions, such as array_shift() and array_pop(), to access array elements. These methods are easy to understand and implement, and you should choose the one that best fits your use case in real-world programming.