'What's the best way to get the last element of an array without deleting it?
Ok,
I know all about array_pop(), but that deletes the last element. What's the best way to get the last element of an array without deleting it?
EDIT: Here's a bonus:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
or even
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4
Solution 1:[1]
Try
$myLastElement = end($yourArray);
Link to manual.
Or a PHP >= 7.3.0 solution:
(Which unlike
end(...), does not change internal iterator.)
$myLastElement = $yourArray[array_key_last($yourArray)];
Link to manual
Solution 2:[2]
Short and sweet.
I came up with solution to remove error message and preserve one-liner form and efficient performance:
$lastEl = array_values(array_slice($array, -1))[0];
-- previous solution
$lastEl = array_pop((array_slice($array, -1)));
Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference.
Solution 3:[3]
What's wrong with array_slice($array, -1)? (See Manual: http://us1.php.net/array_slice)
array_slice() returns an array. Probably not what you are looking for. You want the element.
Solution 4:[4]
One way to avoid pass-by-reference errors (eg. "end(array_values($foo))") is to use call_user_func or call_user_func_array:
// PHP Fatal error: Only variables can be passed by reference
// No output (500 server error)
var_dump(end(array(1, 2, 3)));
// No errors, but modifies the array's internal pointer
// Outputs "int(3)"
var_dump(call_user_func('end', array(1, 2, 3)));
// PHP Strict standards: Only variables should be passed by reference
// Outputs "int(3)"
var_dump(end(array_values(array(1, 2, 3))));
// No errors, doesn't change the array
// Outputs "int(3)"
var_dump(call_user_func('end', array_values(array(1, 2, 3))));
Solution 5:[5]
If you don't care about modifying the internal pointer (the following lines support both indexed and associative arrays):
// false if empty array
$last = end($array);
// null if empty array
$last = !empty($array) ? end($array) : null;
If you want an utility function that doesn't modify the internal pointer (because the array is passed by value to the function, so the function operates on a copy of it):
function array_last($array) {
if (empty($array)) {
return null;
}
return end($array);
}
Though, PHP produces copies "on-the-fly", i.e. only when actually needed. As the end() function modifies the array, internally a copy of the whole array (minus one item) is generated.
Therefore, I would recommend the following alternative that is actually faster, as internally it doesn't copy the array, it just makes a slice:
function array_last($array) {
if (empty($array)) {
return null;
}
foreach (array_slice($array, -1) as $value) {
return $value;
}
}
Additionally, the "foreach / return" is a tweak for efficiently getting the first (and here single) item.
Finally, the fastest alternative but for indexed arrays (and without gaps) only:
$last = !empty($array) ? $array[count($array)-1] : null;
For the record, here is another answer of mine, for the array's first element.
Solution 6:[6]
I need this quite often to deal with stacks, and i always find myself baffled that there's no native function that does it without manipulating the array or its internal pointer in some form.
So i usually carry around a util function that's also safe to use on associative arrays.
function array_last($array) {
if (count($array) < 1)
return null;
$keys = array_keys($array);
return $array[$keys[sizeof($keys) - 1]];
}
Solution 7:[7]
untested: wouldn't this work?
<?php
$last_element=end(array_values($array));
?>
Since the array returned by array_values is fleeting, no-one cares if it's pointer is reset.
and if you need the key to go with it I guess you'd do:
<?php
$last_key=end(array_keys($array));
?>
Solution 8:[8]
To get the last element of an array, use:
$lastElement = array_slice($array, -1)[0];
Benchmark
I iterated 1,000 times, grabbing the last element of small and large arrays that contained 100 and 50,000 elements, respectively.
Method: $array[count($array)-1];
Small array (s): 0.000319957733154
Large array (s): 0.000526905059814
Note: Fastest! count() must access an internal length property.
Note: This method only works if the array is naturally-keyed (0, 1, 2, ...).
Method: array_slice($array, -1)[0];
Small array (s): 0.00145292282104
Large array (s): 0.499367952347
Method: array_pop((array_slice($array, -1, 1)));
Small array (s): 0.00162816047668
Large array (s): 0.513121843338
Method: end($array);
Small array (s): 0.0028350353241
Large array (s): 4.81077480316
Note: Slowest...
I used PHP Version 5.5.32.
Solution 9:[9]
As of PHP version 7.3 the functions array_key_first and array_key_last has been introduced.
Since arrays in PHP are not strict array types, i.e. fixed sized collections of fixed sized fields starting at index 0, but dynamically extended associative array, the handling of positions with unknown keys is hard and workarounds do not perform very well. In contrast real arrays would be internally addressed via pointer arithmethics very rapidly and the last index is already known at compile-time by declaration.
At least the problem with the first and last position is solved by builtin functions now since version 7.3. This even works without any warnings on array literals out of the box:
$first = array_key_first( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
$last = array_key_last ( [1, 2, 'A'=>65, 'B'=>66, 3, 4 ] );
Obviously the last value is:
$array[array_key_last($array)];
Solution 10:[10]
end() will provide the last element of an array
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
echo end($array); //output: c
$array1 = array('a', 'b', 'c', 'd');
echo end($array1); //output: d
Solution 11:[11]
For me:
$last = $array[count($array) - 1];
With associatives:
$last =array_values($array)[count($array - 1)]
Solution 12:[12]
How about:
current(array_slice($array, -1))
- works for associative arrays
- works when
$array == [](returnsfalse) - doesn't affect the original array
Solution 13:[13]
How about this?
Eg-
$arr = [1,2,3];
$lastElem = count($arr) ? $arr[count($arr) - 1] : null;
Solution 14:[14]
$lastValue = end(array_values($array))
No modification is made to $array pointers. This avoids the
reset($array)
which might not be desired in certain conditions.
Solution 15:[15]
One more possible solution...
$last_element = array_reverse( $array )[0];
Solution 16:[16]
The top answers are great, but as mentioned by @paul-van-leeuwen and @quasimodos-clone, PHP 7.3 will introduce two new functions to solve this problem directly - array_key_first() and array_key_last().
You can start using this syntax today with the following polyfill (or shim) functions.
// Polyfill for array_key_last() available from PHP 7.3
if (!function_exists('array_key_last')) {
function array_key_last($array) {
return array_slice(array_keys($array),-1)[0];
}
}
// Polyfill for array_key_first() available from PHP 7.3
if (!function_exists('array_key_first')) {
function array_key_first($array) {
return array_slice(array_keys($array),0)[0];
}
}
// Usage examples:
$first_element_key = array_key_first($array);
$first_element_value = $array[array_key_first($array)];
$last_element_key = array_key_last($array);
$last_element_value = $array[array_key_last($array)];
Caveat: This requires PHP 5.4 or greater.
Solution 17:[17]
To do this and avoid the E_STRICT and not mess with the array's internal pointer you can use:
function lelement($array) {return end($array);}
$last_element = lelement($array);
lelement only works with a copy so it doesn't affect the array's pointer.
Solution 18:[18]
For getting the last value from Array :
array_slice($arr,-1,1) ;
For Removing last value form array :
array_slice($arr,0,count($arr)-1) ;
Solution 19:[19]
Another solution:
$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');
$lastItem = $array[(array_keys($array)[(count($array)-1)])];
echo $lastItem;
Solution 20:[20]
As of PHP 7.3, array_key_last is available
$lastEl = $myArray[array_key_last($myArray)];
Solution 21:[21]
You will get last element from an array easily by using below logic
$array = array('a', 'b', 'c', 'd');
echo ($array[count($array)-1]);
Not only last element but you can also get second last, third last and so on by using below logic.
for second last element you have to pass just number 2 in the above statement for example:
echo ($array[count($array)-2]);
Solution 22:[22]
Simply: $last_element = end((array_values($array)))
Doesn't reset the array and doesn't gives STRICT warnings.
PS. Since the most voted answer still hasn't the double parenthesis, I submitted this answer.
Solution 23:[23]
I think this is a slight improvement on all the existing answers:
$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
- Performs better than
end()or solutions usingarray_keys(), especially with large arrays - Won't modify the array's internal pointer
- Won't try to access an undefined offset for empty arrays
- Will work as expected for empty arrays, indexed arrays, mixed arrays, and associative arrays
Solution 24:[24]
Nowadays, I'd prefer always having this helper, as suggested at an php.net/end answer.
<?php
function endc($array) {
return end($array);
}
$items = array('one','two','three');
$lastItem = endc($items); // three
$current = current($items); // one
?>
This will always keeps the pointer as it is and we will never have to worry about parenthesis, strict standards or whatever.
Solution 25:[25]
Use the end() function.
$array = [1,2,3,4,5];
$last = end($array); // 5
Solution 26:[26]
Note: For (PHP 7 >= 7.3.0) we can use array_key_last — Gets the last key of an array
array_key_last ( array $array ) : mixed
Solution 27:[27]
Most solutions here are unreliable for unassociated arrays, because if we have an unassociated array with the last element being false, then end and current(array_slice($array, -1)) will also return false so we can't use false as an indicator of an empty unassociated array.
// end returns false form empty arrays
>>> $arr = []
>>> end($arr)
=> false
// last element is false, so end returns false,
// now we'll have a false possitive that the array is empty
>>> $arr = [1, 2, 3, false]
>>> end($arr)
=> false
>>> $arr = [1, 2, 3, false, 4]
>>> end($arr)
=> 4
Same goes for current(array_slice($arr, -1)):
// returns false form empty arrays
>>> $arr = []
>>> current(array_slice($arr, -1))
=> false
// returns false if last element is false
>>> $arr = [1, 2, 3, false]
>>> current(array_slice($arr, -1))
=> false
>>> $arr = [1, 2, 3, false, 4]
>>> current(array_slice($arr, -1))
=> 4
Best option is to use array_key_last which is available for PHP >= 7.3.0 or for older versions, we use count to get the last index (only for unassociated arrays):
// returns null for empty arrays
>>> $arr = []
>>> array_key_last($arr)
=> null
// returns last index of the array
>>> $arr = [1, 2, 3, false]
>>> array_key_last($arr)
=> 3
// returns last index of the array
>>> $arr = [1, 2, 3, false, 4]
>>> array_key_last($arr)
=> 4
For older versions, we can use count:
>>> $arr = []
>>> if (count($arr) > 0) $arr[count($arr) - 1]
// No excecution
>>> $arr = [1, 2, 3, false]
>>> if (count($arr) > 0) $arr[count($arr) - 1]
=> false
>>> $arr = [1, 2, 3, false, 4]
>>> if (count($arr) > 0) $arr[count($arr) - 1]
=> 4
That's all for unassociated arrays. If we are sure that we have associated arrays, then we can use end.
Solution 28:[28]
What if you want to get the last element of array inside of the loop of it's array?
The code below will result into an infinite loop:
foreach ($array as $item) {
$last_element = end($array);
reset($array);
if ($last_element == $item) {
// something useful here
}
}
The solution is obviously simple for non associative arrays:
$last_element = $array[sizeof ($array) - 1];
foreach ($array as $key => $item) {
if ($last_element == $item) {
// something useful here
}
}
Solution 29:[29]
$file_name_dm = $_FILES["video"]["name"];
$ext_thumb = extension($file_name_dm);
echo extension($file_name_dm);
function extension($str){
$str=implode("",explode("\\",$str));
$str=explode(".",$str);
$str=strtolower(end($str));
return $str;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
