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:
// A sample indexed array $cities = ["Milan", "London", "Paris"]; echo $cities; // 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.
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:
$array = [3 => "Apple", 5 => "Ball", 11 => "Cat"]; echo array_values($array); // Outputs: Apple
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:
$arr = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; echo reset($arr); // Echoes "apple"
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:
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; $values = array_values($array); echo array_shift($values);
The example of using array_pop to get the first element of an array in PHP is shown below:
$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 keyIf you want to find the first key of the array instead of the value you should use the array_keys function.
$array = [4 => 'apple', 7 => 'banana', 13 => 'grapes']; $keys = array_keys($array); echo $keys;