Friday, 13 July 2018

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

In PHP, there are several ways and many tricks to get the first element of an array. We'll look at some of them in this article. Please note that we'll be using the following array for all the examples:
$names = array(
    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;
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_get_first(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);
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.

Non-Destructive Method (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 non-destructively (i.e. without affecting the original array).

Using array_slice()

// PHP 5.4+
echo array_slice($names, 0, 1)[0];
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); NULL if array is empty
echo array_pop($names_copy); NULL if array is empty
echo implode($names_copy); returns a string representation of the first array element
  • 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];
This method may only be useful if the array is known to not be empty.

Using array_reverse()

// PHP 4+
array_pop(array_reverse($names));
  • 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.

0 comments:

Post a Comment