How to Get the First Element of an Array in PHP
In this post we will give you information about How to Get the First Element of an Array in PHP. Hear we will give you detail about How to Get the First Element of an Array in PHPAnd how to use it also give you demo for it if it is necessary.
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
?>
Hope this code and post will helped you for implement How to Get the First Element of an Array in PHP. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs