How to get the first element of an array in PHP?
Answer: By Accessing the 0 index
We can get the first element of the given array by accessing the 0 index because the indexing of the array elements starts with 0 (zero) instead of 1. So, by accessing the 0 index of the given array, we can get the first array element.
Example: Get First Element by accessing the 0 index
In the given example, we can get the first element of an array by accessing the 0 index.
<!DOCTYPE html>
<html>
<head>
<title>Getting the first element of an array</title>
</head>
<body>
<?php
$arr = array("HTML", "CSS", "JavaScript", "jQuery", "PHP");
echo $arr[0];
?>
</body>
</html>
HTML
Using reset()
function
We can also get the first element of an array using the PHP reset()
function. This function moves the internal pointer to the first element of the array.
Example: Using reset()
function
In the given example, we can get the first element of an array using the reset()
function.
<!DOCTYPE html>
<html>
<head>
<title>Getting the first element of an array</title>
</head>
<body>
<?php
$arr = array("HTML", "CSS", "JavaScript", "jQuery", "PHP");
$my_val = reset($arr);
echo $my_val;
?>
</body>
</html>
HTML
Using current()
function
With the help of the current()
function, we can get the first element of the given array. This function returns the value of the current element within the array. Each array consists of an internal pointer to its current element. The internal pointer is initialized to the first element inserted into the array.
Example: Using current()
function
In this example, we can get the first element of an array using the current() f
unction.
<!DOCTYPE html>
<html>
<head>
<title>Getting the first element of an array</title>
</head>
<body>
<?php
$arr = array("C++", "C", "JavaScript", "jQuery", "PHP");
$my_val = current($arr);
echo $my_val;
?>
</body>
</html>
C++
Conclusion
In this lesson, we have learned how to get the first element of the array in PHP. Here we have discussed three methods to get the first element of an array. At first, we get the first element of an array by accessing the 0 index then we have used the PHP predefined reset()
and last we used the current()
function to get the first element of an array.