get First element of a PHP array

How to get First element of a PHP array?

Getting the first element of a PHP numeric array is easy, but getting the first element of an associative array is a bit challenging.

Here’s how we can get the first element from both types of arrays.

1. Get the first element of a PHP numeric array

You can get the first element with the help of the index number 0.

<?php
$fruits = ["Banana", "Strawberry", "Apple"];
echo  $fruits[0];
Banana

Tip:

One thing you have to note is that if the array is empty then it will give you an error. Therefore, verify whether the array is empty before using it.

<?php
$fruits = ["Banana", "Strawberry", "Apple"];

if (!empty($fruits)) echo $fruits[0];

2. Get the first element of a PHP associative array

Use the reset() function to get first element of an associative array.

reset() – this built-in function sets the internal pointer of an array to its first element then it returns the value of the first array element, or false if the array is empty.

<?php
$fruits = ["a" => "Apple", "b" => "Banana", "C" => "Coconut"];

echo reset($fruits);
Apple

3. Get the first element of any type of PHP array

Build a custom function that will return the first element of any type of PHP array.

In the following code, you can see that I have written a function called get_first_el(array) that will return the first element of any type of array.

get_first_el(array) – this function takes an array as an argument and it will return false if the given array is empty.

<?php
$fruits = ["a" => "Apple", "b" => "Banana", "C" => "Coconut"];
$users = ["Baburao", "Raju", "Shyam"];

function get_first_el(array $arr){
    return empty($arr) ? false : array_values($arr)[0];
}

echo get_first_el($fruits);
echo "\n";
echo get_first_el($users);
Apple
Baburao