How to Get the First Element of an Array in PHP

  184 views   3 months ago PHP

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:

// 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:

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


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on

Related Articles