How To Get The First Element Of An Array In PHP?

Analysis and round-up of various techniques to get the first element of a PHP array

  • By Daniyal Hamid
  • May 26, 2019
  • Comments
In This Article

Get First Element Of An Array With Sequential Numeric Indexes

It's fairly easy and straightforward to get the first element of a sequential array in PHP. Consider for example the following array:

$sequentialArray = ['foo', 'bar', 'baz'];

Accessing The First Element Of Array Directly:

echo $sequentialArray[0] ?? ''; // output: 'foo'

By using ?? (the null coalescing operator) we can return the first index if it's set and not null or return an empty string otherwise.

Using list():

// PHP 4+
list($first) = $sequentialArray;

// or, alternatively in PHP 7.1+
[$first] = $sequentialArray;

echo $first; // output: 'foo'

For a non-sequential array this would throw an error because list() tries to unpack array values sequentially (starting from the first index -- i.e. 0). However, starting from PHP 7.1, you can specify the specific key you're looking to unpack but we're not covering that since it's not within the scope of this article.

Get First Element Of An Out-of-order or Non-sequential Array

In PHP, there are a number of ways we could access the value of the first element of an out-of-order or non-sequential array. We'll look at some of these below. Please note that we'll be using the following array for all the examples that follow:

$names = [9 => 'john', 15 => 'jane', 22 => 'wayne'];

Using foreach Loop:

We can simply make use of the foreach loop to go one round and immediately break (or return) after we get the first value of the array. Consider the code below:

// PHP 4+
foreach($names as $name) {
    echo $name;
    break; // break loop after first iteration
}

// or the shorter form
foreach($names as $name) break; // break loop after first iteration
echo $name; // output: 'john'

Although it takes up a few lines of code, this would be the fastest way as it's using the language construct foreach rather than a function call (which is more expensive).

This could be written as a neat little function as well for easy/frequent use:

function array_first_value(array $a) {
    foreach ($a as $fv) {
        return $fv;
    }
    
    return null; // return null if array is empty
}

Using reset():

The PHP reset() function not only resets the internal pointer of the array to the start of the array, but also returns the first array element, or false if the array is empty. This method has a simple syntax and support for older PHP versions:

// PHP 4+
echo reset($names); // output: "john"

Be careful when resetting the array pointer as each array only has one internal pointer and you may not always want to reset it to point to the start of the array.

Without Resetting The Original Array:

If you do not wish to reset the internal pointer of the array, you can work around it by creating a copy of the array simply by assinging it to a new variable before the reset() function is called, like so:

$names_copy = $names;
next($names); // move array pointer to 2nd element

echo reset($names_copy); // output: "john"
echo current($names); // output: "jane"

As you can see from the results, we've obtained the first element of the array without affecting the original.

Using array_slice():

// PHP 5.4+
echo array_slice($names, 0, 1)[0]; // output: "john"

Please note that by default array_slice() reorders and resets the numeric array indices. This can be changed however, by specifying the fourth parameter preserve_keys as true.

The advantage to using this approach is that it doesn't modify the original array. However, on the flip side there could potentially be an array offset problem when the input array is empty. To resolve that, since our array only has one element, we could use the following methods to return the first (also the only) element:

// PHP 4+
$names_copy = array_slice($names, 0, 1);

echo array_shift($names_copy); output: null if array is empty
echo array_pop($names_copy); output: null if array is empty
echo implode($names_copy); output: '' if array is empty

// PHP 7+
echo $names_copy[0] ?? ''; output: '' if array index is not set or its value is null
  • You must note though that using array_shift() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged.
  • Using both array_shift() and array_pop() resets the array pointer of the input array after use, but in our case that doesn't matter since we're using a copy of the original array, that too with only a single element.

Using array_values():

// PHP 5.4+
echo array_values($names)[0]; // output: "john"

This method may only be useful if the array is known to not be empty.

In PHP 7+, we can use ?? (the null coalescing operator) to return the first index if it's set and not null, or return an empty string otherwise. For example:

// PHP 7+
echo array_values($names)[0] ?? '';

Using array_reverse():

// PHP 4+
array_pop(array_reverse($names)); // output: "john"
  • By default array_reverse() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as true.
  • This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.

Do you know of any other (or better) methods of getting the first element of an array in PHP? Do let us know in the comments section below!