In this tutorial we will see How To Get First Element Of Array In PHP. PHP foreach loop, array_key_first function, array_values() function, reset() function and current() function can be used to get the first element of array.
Table of Contents
Using PHP foreach loop
PHP foreach loop loops through each key/value pair of an array. It only works with array.
We can use foreach loop in PHP to get the first element of array. This is simplest and probably the best method to get it done.
Take a look at the code given below.
<?php
$array = ['HTML', 'CSS', 'JavaScript', 'PHP', 'JQUERY'];
foreach($array as $value)
{
$first_element = $value;
break;
}
echo $first_element;
?>
Output
HTML
In above example we have used foreach loop to get the first element of array.
We have used break statement to exit the loop on first iteration. This will always get us the first element of array.
Using PHP array_values() Function
PHP array_values() Function returns an array of all values of the array but this array will have numeric keys starting from 0. Which means for the first value or first element of array we can use 0 as a key.
That is why we can use array_values() to get the first element of array, see the example below.
<?php
$array = ['HTML', 'CSS', 'JavaScript', 'PHP', 'JQUERY'];
$first_element = array_values($array)[0];
echo $first_element;
?>
Output
HTML
Using PHP array_key_first() Function
PHP array_key_first() Function gives the first key of array.
Using this first key, you can get the first element of array. This method will only work with PHP 7.3 or higher.
Take a look at the code given below.
<?php
$array = ['HTML', 'CSS', 'JavaScript', 'PHP', 'JQUERY'];
$key = array_key_first($array);
$first_element = $array[$key];
echo $first_element;
?>
Output
HTML
Using PHP reset() Function
PHP reset() Function moves the internal pointer to the first element of the array.
reset() Function can also be used to get the first element of array. It returns first element of array if it's not empty, otherwise False is returned.
<?php
$array = ['HTML', 'CSS', 'JavaScript', 'PHP', 'JQUERY'];
$first_element = reset($array);
echo $first_element;
?>
Output
HTML
Using PHP current() Function
PHP current() Function returns the element of array which is currently being pointed by the internal pointer of array.
current() Function is often used to get the first element of array in PHP.
<?php
$array = ['HTML', 'CSS', 'JavaScript', 'PHP', 'JQUERY'];
$first_element = current($array);
echo $first_element;
?>
Output
HTML