How to Get the First Element of an Array in PHP?

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) you 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 you could access the value of the first element of an out-of-order (or non-sequential) array. Please note that we'll be using the following array for all the examples that follow:

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

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 assigning it to a new variable before the reset() function is called, like so:

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

echo reset($namesCopy); // 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+
$namesCopy = array_slice($names, 0, 1);

echo array_shift($namesCopy); // output: null if array is empty
echo array_pop($namesCopy); // output: null if array is empty
echo implode($namesCopy); // 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.

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 reusable function as well:

function array_first_value(array $arr) {
    foreach ($arr as $fv) {
        return $fv;
    }

    return null; // return null if array is empty
}

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.