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
// 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
?>
In the circumstances when you don’t know the exact key or index of the array, you can use the functions that are demonstrated below.
Using array_values()
In the circumstances when you don’t know the exact key or index of the array, you can use the array_values() function. It is capable of returning all the values of the array and indexing the array numerically.
The example of using array_values() is demonstrated below:
<?php
$array = [3 => "Apple", 5 => "Ball", 11 => "Cat"];
echo array_values($array)[0]; // Outputs: Apple
?>
Using reset()
Now, let’s consider an alternative method to get the first element of an array.
It is the PHP reset() function. It is used for setting the internal pointer of the array to its first element and returning the value of the first array element. In the case of a failure, it returns FALSE or an empty array.
Here is an example:
<?php
$arr = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
echo reset($arr); // Echoes "apple"
?>
Using array_shift
Another helpful method of getting the first element of a PHP array is using array_shift.
The example of using the array_shift function will look as follows:
<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
$values = array_values($array);
echo array_shift($values);
?>
Using array_pop
The example of using array_pop to get the first element of an array in PHP is shown below:
<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
$reversedArray = array_reverse($array);
echo array_pop($reversedArray);
?>
After checking out all the methods and examples above, you can choose the one that suits your project more.
How to find the first key
If you want to find the first key of the array instead of the value you should use the array_keys function.<?php
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes'];
$keys = array_keys($array);
echo $keys[0];
?>
4