How can I get the last key of an array?
18 Answers
A solution would be to use a combination of end
and key
(quoting) :
end()
advances array 's internal pointer to the last element, and returns its value.key()
returns the index element of the current array position.
So, a portion of code such as this one should do the trick :
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
Will output :
string 'last' (length=4)
i.e. the key of the last element of my array.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset()
on the array to bring the pointer back to the beginning of the array.

- 266
- 1
- 12

- 395,085
- 80
- 655
- 663
-
19@Pim : depends on what the OP wants to do with that array after *(might not be needed to call `reset()`)* ;; but you're right in pointing that function, which could be useful. – Pascal MARTIN Feb 27 '10 at 17:16
-
3@PascalMARTIN +1 I think adding a comment about the reset() in your answer will be very helpful. – Lulu Dec 08 '15 at 23:01
-
This approach does not work if the array has duplicate values. eg. for `array('a', 'b', 'c', 'd', 'a')` it will return key 0 rather than 4. – Marc Feb 12 '16 at 15:50
-
3
-
Thanks Jeff. I've just tried it again, and you're absolutely right! I must have been doing it some other (wrong) way before. – Marc Mar 11 '16 at 08:56
-
much better is to `reset()` (or other way to get control over the pointer) right **before** you're going to work with pointer. It's safer then rely on previous code he cleaned his mess up. – hejdav Sep 19 '16 at 11:31
-
@hejdav : Given an array of n values : end() isn't just like the opposite of reset() (putting the pointer at an absolute value, either at 0 or at n) ? So if you work with pointers with end(), no need to reset() before I guess – tomsihap Jan 12 '17 at 13:06
-
-
1@pppp it doesn't work because... check what end() returns and then think again ;) – forsberg Mar 07 '18 at 17:24
Although end()
seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice()
:
$lastKey = key(array_slice($array, -1, 1, true));
As the tests say, on an array with 500000 elements, it is almost 7x faster!

- 3,728
- 2
- 33
- 40

- 2,765
- 1
- 25
- 41
-
103excited by this answer, i did a quick test of 100,000 iterations, comparing (a) `end($arr);$key = key($arr);reset($arr);` against (b) `$key = key(array_slice($arr,-1,1,true));` ... which resulting in `end()` being MUCH faster! end() = 0.05326 seconds, array_slice = 8.506 seconds ... huh?? – designosis Sep 26 '12 at 07:00
-
56PHP's built-in functions were built by extreme nerds. Do not try to recreate those functions. The odds are that you make something far slower than the original. Unless you are some sort of evil wizard, of couse. – dmmd Mar 18 '13 at 04:32
-
17`end()` is fastest because it can be derived from a very simple C-function, such as: `int top(void){ int i; for(i = 0; stack[i] != '\0'; i++); return stack[--i]; }` – Gustav Jun 18 '13 at 18:37
-
10@Gustav I believe the underlying C-implementation of PHP, actually have an internal pointer `last` to the last element. Making `end()` pretty much O(1). :-) – Eric Aug 05 '14 at 08:55
-
16@dmmd, I'm sure PHP team would be extreme pleased they are called nerds. – datasn.io Apr 03 '15 at 09:51
-
2this is perfect. i wanted the last and second to last elements. accepted answer only answered for last – iedoc Apr 14 '15 at 16:08
-
1I wonder why @tadoman or @Matt didn't defend the claim that this solution is faster than calling `end()`. – Mr. Lance E Sloan Feb 03 '17 at 13:45
-
1I'm really surprised why someones say `end()` is faster! I don't know what the internals or math says (if they are correct), or if PHP developers are skillful or not. The tests say that this solution is really faster than `end()`. Besides, its performance become increasingly better when the array size increases. [Testing on an array with 500000 elements](https://3v4l.org/tE7RN), `array_slice()` performance is 4x to 10x faster than `end()`. After `array_key_last()`, this solution might be the most efficient solution on the earth! – MAChitgarha Jul 12 '19 at 15:41
-
@MAChitgarha I was really surprised to see that you included the `reset()` call (which is not the point being argued relating to performance) in your speed comparison. I removed the `reset()` call, ran the script again, and found the performance gap increased! I haven't bothered to scrutinize your benchmarking script, but why would `end()`-`key()` process perform worse after removing a function call? Makes me wonder if there is something off about your benchmarking script. Any thoughts on that? – mickmackusa Jul 30 '19 at 12:30
-
@mickmackusa I found it surprising too! I don't really know why the performance decreases when `reset()` is removed. Amazing thing. Maybe it's something related to internals. However, after reviewing the code, nothing looks strange, and the code is simple; but to make reviewing simpler, look at [this code](https://3v4l.org/vptLm). The results shows this solution is around 10x faster than `end()` + `key()` + `reset()`. – MAChitgarha Jul 30 '19 at 13:58
-
2@MAChitgarha Thank you for your effort with the benchmarking. I have extended [my answer to make some additional technique comparisons using your benchmark script](https://stackoverflow.com/a/52098132/2943403). It seems that all of the debate on this page can be definitively put to bed as of PHP7.3 since `array_key_last()` is obviously the new gold standard. – mickmackusa Jul 30 '19 at 23:22
-
@mickmackusa Oh, good up-to-date answer. Thanks for the benchmarks! – MAChitgarha Jul 31 '19 at 14:17
Since PHP 7.3 (2018) there is (finally) function for this: http://php.net/manual/en/function.array-key-last.php
$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )
will output
orange

- 1,081
- 7
- 7
-
5Horray! I was about to add this answer. Could you highlight the "PHP 7.3" version and 2018 year? It will be easier to spot this awesome news for others – Tomas Votruba Aug 16 '18 at 21:18
-
6Also good to mention that this does NOT affect the internal array pointer. – mvorisek Jun 06 '19 at 09:57
I prefer
end(array_keys($myarr))

- 7,964
- 2
- 24
- 24
-
20
-
26
-
9@BenFortune This has been fixed in PHP7: "In PHP 5, using redundant parentheses around a function parameter could quiet strict standards warnings when the function parameter was passed by reference. The warning will now always be issued." – Dominic Scheirlinck Jan 18 '16 at 01:05
-
that's a totally unnecessary warning! it's such a normal and usual stuff in all other languages! – azerafati Feb 06 '16 at 16:38
-
1In other languages, the functions don't operate on pointers, do they? – jurchiks Sep 01 '16 at 23:29
-
The manual says the argument "is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference." That makes sense, but I'd prefer a function that doesn't modify the array. – Mr. Lance E Sloan Feb 03 '17 at 13:56
-
An advantage of using `end()` on the results of `array_keys($myarr)` rather than `$myarr` directly is that the array's internal pointer doesn't get changed. That's good if other parts of the program depend on the array's internal pointer. – Mr. Lance E Sloan Feb 03 '17 at 14:00
-
This method should never be used over the accepted answer. Not only does it generate a NOTICE, generating a whole new array of keys just to pluck one from it is going to be less efficient than PascalMARTIN's method (increasingly so, as the original array increases in length). Because there are other more efficient answers that do not trigger a NOTICE, I am downvoting this answer – mickmackusa Apr 19 '17 at 05:39
-
-
Only variables can be passed by reference for end() you need to creat as $array1 = array_keys($myarr); end($array1); – megyptm May 07 '23 at 13:17
Just use : echo $array[count($array) - 1];

- 561
- 4
- 2
-
79This only works if you have numerical arrays. Fails with associate arrays. – Jeremy J Starcher Sep 21 '12 at 04:15
-
16Not only does this only work on numerical arrays, it fails to show the key but shows the value, doesn't it? – Nanne Oct 22 '13 at 07:59
-
me too jake, can we do a thing where we split this (lets be honest) top google hit into both numerical and associative so that we have a old reference for both... I only worked out it was for assoc after parsing `int top(void){ int i; for(i = 0; stack[i] != '\0'; i++); return stack[--i]; }` which is interesting but not good for business when you're on a time budget – lol Apr 24 '14 at 16:32
-
5Also, even for a numerical array, keep in mind that numerical arrays do not have to go in order, or use all the numbers. This will work if you do not explicitly assign to numeric values, but if you do `$a[1] = 1; $a[5] = 5; $a[0] = 0;` Then you will have an array with keys (1, 5, 0), in that order. `count($a)` will yield 3 and `$a[2]` is not defined. It certainly doesn't give you 5 back. – Daniel Skarbek Jul 10 '14 at 01:33
-
This answer doesn't work for all array situations and is going to be wrong more times than it is going to be right. Because the OP doesn't declare an input array, correct answers must be able to deal with all possible arrays with at least one value. Downvote. – mickmackusa Apr 19 '17 at 05:21
-
Downvoting because there are too many problems with this as per other comments: Ignoring the issue that it doesn't answer the question, it only works for non-associative arrays and only then if the indices were created in the right order and none of the elements has been unset. It IS useful but the answer should have noted the caveats instead of allowing the impression that it was a generic answer to a generic question. – Nick Rice Dec 13 '17 at 11:15
-
2
-
This is so wrong, lol. The OP asked for the last key, not the last value. – DrLightman Mar 14 '21 at 20:39
-
Hopefully with the new trending sort, people will STOP UVING this clearly incorrect answer so that it can be purged by curators!!!! – mickmackusa Mar 25 '22 at 00:14
Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...
it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
$keys = array_keys($array);
$last = end($keys);

- 290
- 2
- 4
-
3This answer (while technically correct) is wasteful/inefficient because it requires the creation of an additional array (of equal length as the original). This means that the waste increases as the original array does. This should never be chosen over Pascal MARTIN's efficient answer. I am surprised this has so many upvotes. – mickmackusa Apr 19 '17 at 05:17
As of PHP7.3 you can directly access the last key in (the outer level of) an array with array_key_last()
The definitively puts much of the debate on this page to bed. It is hands-down the best performer, suffers no side effects, and is a direct, intuitive, single-call technique to deliver exactly what this question seeks.
A rough benchmark as proof: https://3v4l.org/hO1Yf
array_slice() + key(): 1.4 end() + key(): 13.7 array_key_last(): 0.00015
*test array contains 500000 elements, microtime repeated 100x then averaged then multiplied by 1000 to avoid scientific notation. Credit to @MAChitgarha for the initial benchmark commented under @TadejMagajna's answer.
This means you can retrieve the value of the final key without:
- moving the array pointer (which requires two lines of code) or
- sorting, reversing, popping, counting, indexing an array of keys, or any other tomfoolery
This function was long overdue and a welcome addition to the array function tool belt that improves performance, avoids unwanted side-effects, and enables clean/direct/intuitive code.
Here is a demo:
$array = ["a" => "one", "b" => "two", "c" => "three"];
if (!function_exists('array_key_last')) {
echo "please upgrade to php7.3";
} else {
echo "First Key: " , key($array) , "\n";
echo "Last Key: " , array_key_last($array) , "\n";
next($array); // move array pointer to second element
echo "Second Key: " , key($array) , "\n";
echo "Still Last Key: " , array_key_last($array);
}
Output:
First Key: a
Last Key: c // <-- unaffected by the pointer position, NICE!
Second Key: b
Last Key: c // <-- unaffected by the pointer position, NICE!
Some notes:
array_key_last()
is the sibling function of array_key_first().- Both of these functions are "pointer-ignorant".
- Both functions return
null
if the array is empty. - Discarded sibling functions (
array_value_first()
&array_value_last()
) also would have offered the pointer-ignorant access to bookend elements, but they evidently failed to garner sufficient votes to come to life.
Here are some relevant pages discussing the new features:
- https://laravel-news.com/outer-array-functions-php-7-3
- https://kinsta.com/blog/php-7-3/#array-key-first-last
- https://wiki.php.net/rfc/array_key_first_last
p.s. If anyone is weighing up some of the other techniques, you may refer to this small collection of comparisons: (Demo)
Duration of array_slice() + key(): 0.35353660583496 Duration of end() + key(): 6.7495584487915 Duration of array_key_last(): 0.00025749206542969 Duration of array_keys() + end(): 7.6123380661011 Duration of array_reverse() + key(): 6.7875385284424 Duration of array_slice() + foreach(): 0.28870105743408

- 43,625
- 12
- 83
- 136
As of PHP >= 7.3 array_key_last()
is the best way to get the last key of any of an array. Using combination of end()
, key()
and reset()
just to get last key of an array is outrageous.
$array = array("one" => bird, "two" => "fish", 3 => "elephant");
$key = array_key_last($array);
var_dump($key) //output 3
compare that to
end($array)
$key = key($array)
var_dump($key) //output 3
reset($array)
You must reset array for the pointer to be at the beginning if you are using combination of end()
and key()

- 7,507
- 3
- 52
- 52

- 281
- 1
- 3
- 7
Try using array_pop and array_keys function as follows:
<?php
$array = array(
'one' => 1,
'two' => 2,
'three' => 3
);
echo array_pop(array_keys($array)); // prints three
?>

- 445,704
- 82
- 492
- 529
-
14This is really slow if your array has more than 1 thing in it. Please don't do this. – Andrey Oct 07 '10 at 18:11
-
3
-
array_pop() would shorten the original array (removing the last element). I'm not sure whether this matters or not for the OP but will certainly matter to others. – Programster Jan 13 '17 at 08:04
-
1Not really. In this example `array_pop()` operates on the return value of `array_keys()` and _not_ on the original array. – Petko Bossakov Jan 23 '17 at 07:16
-
Because there are other more efficient answers that do not trigger a NOTICE, I am downvoting this answer. – mickmackusa Apr 19 '17 at 05:43
-
@Andrey It's slower, but not really slow. The performance does not reach two times slower (i.e. no 100% performance cost). – MAChitgarha Jul 12 '19 at 14:51
It is strange, but why this topic is not have this answer:
$lastKey = array_keys($array)[count($array)-1];

- 2,707
- 4
- 29
- 42
-
Because this technique will ONLY work on indexed (gapless integer keys starting from zero) arrays. It simply isn't robust enough for general use. `array_key_last()` (which is suitable for all array structures) was released 6 December 2018 and will not longer be supported from 6 December 2021. Modern applications should have already upgraded their php versions. This explains why this page doesn't need `array_keys($a[count($a) - 1)` as late as 2020. – mickmackusa Mar 25 '22 at 00:09
I would also like to offer an alternative solution to this problem.
Assuming all your keys are numeric without any gaps, my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.
$array = array(0=>'dog', 1=>'cat');
$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];
var_dump($lastKey);
print_r($lastKeyValue);
This would give you:
int(1) cat
-
1This won't work for array's where keys aren't incremental e.g. array(0=>'dog', 5=>'cat'); $lastKey would return a wrong value – kakoma Apr 21 '15 at 08:32
-
1@kakoma - As my post says "Assuming all your keys are numeric without any gaps". – Apr 22 '15 at 13:22
-
For anyone who wonders use PHP's "array_values" to rekey the array to numerical sequential. http://php.net/manual/en/function.array-values.php – Apr 30 '15 at 10:49
-
1Because this answer only deals with a fraction of the array possibilities (numerical, consecutive keyed arrays), this answer does not offer a robust/correct answer to the OP's generalized question. Downvote. – mickmackusa Apr 19 '17 at 05:49
You can use this:
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
end($array);
echo key($array);
Another Solution is to create a function and use it:
function endKey($array){
end($array);
return key($array);
}
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);

- 2,650
- 27
- 34
-
1
-
1
-
1do you need to add 1 line of code into a function? That's a rather needless interface. – Martin Nov 17 '15 at 13:27
-
1
-
2
-
1@AtifTariq Please take this opportunity to earn your **Disciplined Badge** by removing your answer from this page. It is a duplicate of PascalMARTIN's method. (I will withhold my downvote to give you a little time to do so.) – mickmackusa Apr 19 '17 at 04:26
$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3

- 11,861
- 3
- 36
- 40
-
2Reversing the entire array only to pull one value is certainly less efficient than PascalMARTIN's method. Even though it is technically correct, it should never be used in place of Pascal's approach. – mickmackusa Apr 19 '17 at 05:33
I just took the helper-function from Xander and improved it with the answers before:
function last($array){
$keys = array_keys($array);
return end($keys);
}
$arr = array("one" => "apple", "two" => "orange", "three" => "pear");
echo last($arr);
echo $arr(last($arr));

- 47
- 1
$array = array(
'something' => array(1,2,3),
'somethingelse' => array(1,2,3,4)
);
$last_value = end($array);
$last_key = key($array); // 'somethingelse'
This works because PHP moves it's array pointer internally for $array

- 791
- 1
- 6
- 15
-
2This is a duplicate of PascalMARTIN's method. Please spare this page and delete your late/duplicate answer. Downvoted. – mickmackusa Apr 19 '17 at 05:35
The best possible solution that can be also used used inline:
end($arr) && false ?: key($arr)
This solution is only expression/statement and provides good is not the best possible performance.
Inlined example usage:
$obj->setValue(
end($arr) && false ?: key($arr) // last $arr key
);
UPDATE: In PHP 7.3+: use (of course) the newly added array_key_last()
method.

- 3,290
- 2
- 18
- 53
Try this one with array_reverse()
.
$arr = array(
'first' => 01,
'second' => 10,
'third' => 20,
);
$key = key(array_reverse($arr));
var_dump($key);

- 69,473
- 35
- 181
- 253

- 1,290
- 14
- 15
Try this to preserve compatibility with older versions of PHP:
$array_keys = array_keys( $array );
$last_item_key = array_pop( $array_keys );

- 139
- 4
- 14
-
1This fixes [codaddict's snippet](https://stackoverflow.com/a/2348214/2943403), but in 2021, there is no good reason to use this technique (which modifies the original array -- a behavior that was not called for in the question). All devs should be using `array_key_last()` because it is perfectly suited. – mickmackusa Mar 25 '22 at 00:17