How to Get the First Element of an Array in PHP

  1. A. Using array_values()
  2. B. Using reset()
  3. C. Using array_shift
  4. D. Using array_pop

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 = array("Milan", "London", "Paris");
echo $cities[0]; // Outputs: Milan
 
// A sample associative array
$fruits = array("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.

A. 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
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo array_values($arr)[0]; // Outputs: Apple
?>

B. 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:

$arr = array( 4 => 'apple', 7 => 'banana', 13 => 'grapes' ) 
echo reset($arr); // Echoes "apple"

C. 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:

array_shift(array_values($array));

D. Using array_pop

The example of using array_pop to get the first element of an array in PHP is shown below:

array_pop(array_reverse($array));

After checking out all the methods and examples above, you can choose the one that suits your project more.


Do you find this helpful?

Related articles