How to get the first element of an array in PHP?

In PHP, there are several methods to get the first element of an array. The approach depends on whether you're working with indexed arrays, associative arrays, or need to preserve the array pointer.

Using array_values() for First Element

The most reliable method works with both indexed and associative arrays ?

<?php
$arr = array("p" => "150", "q" => "100", "r" => "120", "s" => "110");
echo "First element: " . array_values($arr)[0];
?>
First element: 150

Using reset() Function

The reset() function moves the internal pointer to the first element and returns its value ?

<?php
$arr = array("p" => "150", "q" => "100", "r" => "120", "s" => "110");
echo "First element: " . reset($arr);
?>
First element: 150

Using array_slice() Method

Extract the first element while preserving the array structure ?

<?php
$arr = array("apple", "banana", "cherry", "date");
$first = array_slice($arr, 0, 1)[0];
echo "First element: " . $first;
?>
First element: apple

Comparison

Method Modifies Array Pointer Works with Empty Arrays Performance
array_values()[0] No No (throws error) Medium
reset() Yes No (returns false) Fast
array_slice() No No (returns empty) Slower

Conclusion

Use reset() for simple cases and array_values()[0] when you need to preserve the array pointer. Always check if the array is not empty before accessing the first element.

Updated on: 2026-03-15T08:18:11+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements