In this article I will explain some methods to solve this problem: how to get the first (or last) element of an array without removing it.
If we execute these two PHP functions:
- array_pop, a function that get the last element of an array and remove it
- array_shift, a function that get the first element of an array and remove it
The element that we get will be removed from the array, but sometimes we just want to get an element without removing it from the array.
Here we have the different methods we have to do this:
2.1. Use of current and end function
We have different functions to get different elements from an array:
that will return the element from the pointer. If we haven’t moved the pointer, then it will return the first element.
that will move the pointer to the last element and then return it
- next($array) and prev($array)
will move the pointer in the array to the next or the previous position.
To understand this, let’s see an example
2.2. Use of array_slice
This function get a sequence of elements of an array but doesn’t modify the array itself. This function accept at least two arguments:
array array_slice ( array
$array , int
$offset [, int
NULL [, bool
$preserve_keys = false ]] )
- $array is the array
- $offset indicates the elements that will be returned from the array. If
offsetis positive, the sequence will start at that position. If is negative, the sequence will start that far from the end of the $array.
3. Example of use
$fruits = array('lemon', 'banana', 'apple', 'orange'); $fruit = current($fruits); // $fruit = 'lemon'; $fruit = next($fruits); // $fruit = 'banana'; $fruit = current($fruits); // $fruit = 'banana'; $fruit = prev($fruits); // $fruit = 'lemon'; $fruit = end($fruits); // $fruit = 'orange'; $fruit = current($fruits); // $fruit = 'orange'; $fruit = reset($fruits); // $fruit = 'lemon'; $fruit = array_pop($fruits); // $fruit = 'orange'; $fruit = array_shift($fruits); // $fruit = 'lemon'; // $fruits = Array (  => banana  => apple )
Do you have some performance measurements? Which one is recommended to use?
I did. The fastest on PHP8 is following:
list($first) = $fruits;
Interesting! I have not used PHP8 yet, so it’s an interesting point, thanks