How To Get The First Element Of Array In PHP?

PHP provides several methods to get the first element of an array. These methods are using the square bracket notation [0], using the reset() Function, and using the array_values() function with the 0 index.

All The Examples #
  1. Using Square Bracket Notation
  2. PHP reset() Function To Get First Array Element
  3. PHP array_values() Function With [0] Index
  4. Wrap The Code Into A Function

1. Using Square Bracket Notation [0]

The most straightforward method to access the first element of an indexed array is by using square bracket notation. PHP arrays are zero-indexed, meaning the first element has an index of 0.

<?php
$array = [10, 20, 30, 40, 50];
$first_element = $array[0];
echo $first_element;  // Output: 10

In this method, we directly access the first element of the array $array using square brackets and index 0. But you need to keep in mind that this method will only work with indexed or numeric arrays.

2. PHP reset() Function To Get First Array Element

The reset() function in PHP rewinds the internal pointer of an array to the first element and returns its value. This reset() function works with both associative and numeric (indexed) arrays.

<?php
// Indexed Array
$myArray = [10, 20, 30, 40, 50];


// Associative Array
$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'date'
);

$firstElement = reset($myArray);
$firstFruit = reset($fruits);

echo $firstElement; // Output: 10
echo $firstFruit; // Output: apple

3. PHP array_values() Function With [0] Index

Another way to get the first element of an array is by using the array_values() function with the 0 index. This function returns all the values of an array as a new indexed array, and you can then access the first element by the index [0].

<?php
// Indexed Array
$myArray = [10, 20, 30, 40, 50];


// Associative Array
$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'date'
);

$firstElement = array_values($myArray)[0];
$firstFruit = array_values($fruits)[0];

echo $firstElement; // Output: 10
echo $firstFruit; // Output: apple

4. Wrap The Code Into A Function

<?php
function get_first_element($arr)
{
    // Checking if the parameter is an array and not empty
    if (is_array($arr) && !empty($arr)) {
        return reset($arr);
    }

    return "Invalid Array";
}

$myArray = [50, 20, 30, 40, 10];

echo get_first_element($myArray); // Output: 50