How can I get the first element of an array in PHP?
We’ll show you three ways you can get the first element of an array in PHP:
reset()
and current()
functions, which resets the array’s internal pointer without changing the array.array_pop()
function, which preserves the original array and the position of it’s internal pointer.array_shift()
function to remove the first element from the array.An array’s internal pointer keeps track of which element in the array is currently being referenced. You can use the reset()
function to move the internal pointer to the first element of the array, and then the current()
function to get the value of the element that is being pointed to:
$myArray = [ 'red' => 'apple', 'yellow' => 'banana', 'green' => 'grapes' ]; // ensure the pointer is at the first element reset($myArray); // get the value of the element being pointed to $firstElement = current($myArray); echo $firstElement;
We get the value of the first element:
apple
If you’re working with an array that you’re doing further manipulation on, you might need to preserve the position of the array’s internal pointer. You can preserve the position of the array’s internal pointer and get the first element by reversing the array and using the array_pop()
function to remove and return the last element of the reversed array.
$myArray = [ 'red' => 'apple', 'yellow' => 'banana', 'green' => 'grapes' ]; // create a reversed array of the original $revArray = array_reverse($myArray); // remove the last element $myElement = array_pop($revArray); // output the element and original array echo $myElement .PHP_EOL; print_r($myArray);
Here, we remove the last element of our reversed array, which gives us the first element of our original $myArray
. The output gives us the value of the first element of our original array and the original array:
apple Array ( [red] => apple [yellow] => banana [green] => grapes )
array_shift()
FunctionIn this example, we pass $myArray
into the array_shift()
function to get its first element:
$myArray = [ 'red' => 'apple', 'yellow' => 'banana', 'green' => 'grapes' ]; // get the first element $firstFruit = array_shift($myArray); // output echo $firstFruit .PHP_EOL; print_r($myArray);
Our array_shift()
function returns the value of the first element. We can see from the output that the original array no longer has that element:
// the value of the first element apple // the original array has two remaining elements left Array ( [yellow] => banana [green] => grapes )
Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.