Get The First Element Of Array In PHP
Code snippet for how to Get The First Element Of Array In PHP with sample and detail explanation
PHP offers several array functions, one of them is used to retrieve the first element of an array. This article will guide you to understand how to get the first element of an array in PHP.
Code snippet for getting the first element of an array in PHP
<?php
$array = array("element1", "element2", "element3");
$firstElement = reset($array);
echo $firstElement;
?>
In the above PHP script, the built-in function ‘reset()’ is used to fetch the first array element.
Code Explanation for getting the first element of an array in PHP
Here is the step-by-step explanation to understand the code snippet we have used above:
-
Firstly, we have defined an array by writing
$array = array("element1", "element2", "element3");
.An array is a special variable that can hold more than one value at a time. It has keys and values where keys are indexes and values are the content.
-
The second line of the code
$firstElement = reset($array);
is very crucial in getting the first element of an array.In PHP, the
reset()
function moves the internal pointer to the first element of the array and returns the value of the first array element. -
After we have used the
reset()
function, we are now ready to display the first element of the array. Theecho
statement is used in PHP for this purpose.So, the code
echo $firstElement;
will output the first element of the array, i.e., “element1”.
This is a very efficient and straightforward way to get the first element of an array in PHP. Whether you’re dealing with small arrays or large, multidimensional ones, this function will always give you the first element. Always remember that the reset()
function does not merely return the first element; it also resets the array’s internal pointer to the first element. Hence, the next call to each() would start with the first element. With these steps, you should be able to get the first element of an array in PHP easily.