Last updated on July 27, 2023
In PHP, you can get the first element of an array using various methods. Here are some common ways to achieve this:
Method 1: Using array_shift() The array_shift()
function removes and returns the first element of an array. Here’s how you can use it:
$myArray = [1, 2, 3, 4, 5];
$firstElement = array_shift($myArray);
echo $firstElement; // Output: 1
Method 2: Using reset() The reset()
function moves the internal array pointer to the first element and returns its value. It does not modify the original array.
$myArray = [1, 2, 3, 4, 5];
$firstElement = reset($myArray);
echo $firstElement; // Output: 1
Method 3: Using array_key_first() (PHP 7.3 and later) If you are using PHP 7.3 or later, you can use the array_key_first()
function to get the first key of the array and then access the element using that key.
$myArray = [1 => 'apple', 2 => 'banana', 3 => 'orange'];
$firstKey = array_key_first($myArray);
$firstElement = $myArray[$firstKey];
echo $firstElement; // Output: apple