How can I get the first element of an array in PHP?

How can I get the first element of an array in PHP? The solution is easier than you might think, by using PHP's reset and current, array_pop, or array_shift functions.

Get the first element of an array in PHP

PHP uses array pointers to keep track of which element is currently being used, during the runtime of PHP. If we want to get the first element of an array we can use reset and current, two of which are PHP functions. Using reset tells PHP that we want the pointer to go to the start and current then outputs where the current array index pointer is. Because we've reset the pointer it's going to output the first element of the array.

$array = ['red', 'blue', 'yellow', 'orange'];
reset($array);
echo current($array);

# Outputs 
red

Using array_reverse and array_pop to get the first element of an array

If you require to keep the array pointer in the current position, we can clone the array to another variable and use array_reverse. Here we are reversing the array and then popping off the last element in the array to give us what was the first element of the array. Doing it this way preserves the original array index, helpful if it is being used later.

$array = ['red', 'blue', 'yellow', 'orange'];
$reversedArray = array_reverse($array);
echo array_pop($reversedArray);

# Outputs 
red

Using array_shift to get the first element in an array

Alternatively, we can use array_shift which allows us to obtain the top element in a PHP array. By giving the same array to the function, it will return to the top element.

$array = ['red', 'blue', 'yellow', 'orange'];
echo array_shift($array);

# Outputs 
red

It's important to note that using array_shift to obtain the first element does in the process remove it from the array.

print_r($array);

# Outputs
Array
(
 [0] => blue
 [1] => yellow
 [2] => orange
)

We have many more guides for all PHP skill levels, including a complete guide to PHP arrays and the best way to prevent warning: Undefined array key.

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all