Appearance
How to Get the First Element of an Array in PHP
Here, you have the opportunity of finding the most proper solutions on how to get the first element of an array in PHP. Let’s consider several options below.
Let’s see how to get the first element of an array when you know the particular index or the key of the array. In that case, you can retrieve the first element straightforwardly by running this code:
php get the first element of an array
php
<?php
// A sample indexed array
$cities = ["Milan", "London", "Paris"];
echo $cities[0]; // Outputs: Milan
// A sample associative array
$fruits = ["a" => "Banana", "b" => "Ball", "c" => "Dog"];
echo $fruits["a"];
// Outputs: Banana
?>If you don’t know the exact key or index, you can use the functions demonstrated below.
Using array_values()
The array_values() function reindexes the array numerically and returns all values.
The example of using array_values() is demonstrated below:
php array_values()
php
<?php
$array = [3 => "Apple", 5 => "Ball", 11 => "Cat"];
echo array_values($array)[0]; // Outputs: Apple
?>Using reset()
Another method is the PHP reset() function. It sets the internal array pointer to the first element and returns its value. If the array is empty, it returns FALSE.
Here is an example:
php reset() function
php
<?php
$arr = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
echo reset($arr); // Echoes "apple"
?>Using current()
The current() function returns the value of the current array element without moving the internal pointer. It is a non-mutating alternative to reset().
php
<?php
$arr = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
echo current($arr); // Outputs: apple
?>Using array_shift()
You can also use array_shift() to extract the first element.
php array_shift to get the first element of an array
php
<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
echo array_shift($array); // Outputs: apple
?>Note: array_shift() modifies the original array by removing the first element.
Using array_pop()
You can also use array_pop() combined with array_reverse():
php use array_pop to get the first element of an array
php
<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
$reversedArray = array_reverse($array);
echo array_pop($reversedArray);
?>Note: This approach is inefficient for large arrays because array_reverse() creates a full copy. Prefer reset() or array_shift() for better performance.
Choose the method that best fits your project's needs.
How to find the first key
If you want to find the first key of the array instead of the value, use the array_keys() function.
Example of finding the first key of an array in PHP
php
<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
$keys = array_keys($array);
echo $keys[0];
?>console
4