This post will discuss how to get the first element of an array in PHP without deleting it.

1. Using reset() function

The key() function returns the key of the array element that’s currently being pointed to by the internal pointer. You can set the array’s internal pointer to its first element using the reset() function, which also returns the value of the first element.

Download  Run Code

 
The array’s internal pointer is initialized to the first element of the array. If the array has never been repositioned before, the internal pointer would be pointing to the first element. In such cases, you can directly invoke the current() function to get the value of the first element.

Download  Run Code

2. Using array_key_first() function

The recommended way to get the first key of an array is using array_key_first() function. This function is available with PHP 7.3.0 and above, outperforms reset() function in terms of performance, and avoids any side effects such as losing the current array pointer position.

Since array_key_first() function returns the “key” present at the beginning of the array, you can use the array’s access notation to get the associated value.

Download  Run Code

3. Using array_shift() function

For PHP <= 7.2, you can use the array_slice() function to get the first element of an array. It accepts the offset and length parameters, which represent the starting position, and extracts a slice from the array of the specified length.

Download  Run Code

 
The array_slice() function acts as an efficient alternative to the reset() function. However, it returns an array. To get the value of the first element, you can call the array_shift() function on the slice.

Download  Run Code

4. Using Array Access Notation

You can also access the first element of an array using array access notation. However, this only works with numerical arrays and fails for associative arrays.

Download  Run Code

That’s all about finding the first element of an array in PHP.