Q:

How to Get the First Element of an Array in PHP

0

How to Get the First Element of an Array in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Convert a Date to Timestamp in PHP... >>
<< How to Convert a String to a Number in PHP...