How to Get the First Element of an Array in PHP

Topic: JavaScript / jQueryPrev|Next

Answer: Use the PHP array_values() Function

If you know the exact index or key of an array you can easily get the first element, like this:

  • <?php
  • // A sample indexed array
  • $cities = array("London", "Paris", "New York");
  • echo $cities[0]; // Outputs: London
  • // A sample associative array
  • $fruits = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
  • echo $fruits["a"]; // Outputs: Apple
  • ?>

However, there are certain situations where you don't know the exact index or key of the first element. In that case you can use the array_values() function which returns all the values from the array and indexes the array numerically, as shown in the following example:

  • <?php
  • $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
  • echo array_values($arr)[0]; // Outputs: Apple
  • ?>

Alternativly, you can also use the reset() function to get the first element.

The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

You can also use the current() function to get the first element of an array. This function returns the current element in an array, which is the first element by default unless you've re-positioned the array pointer, otherwise use the reset() function. Here's an example:

  • <?php
  • $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
  • echo current($arr); // Outputs: Apple
  • echo reset($arr); // Outputs: Apple
  • echo next($arr); // Outputs: Ball
  • echo current($arr); // Outputs: Ball
  • echo reset($arr); // Outputs: Apple
  • ?>

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:

We would love to hear from you, please drop us a line.